Click here to Skip to main content
13,894,773 members
Click here to Skip to main content
Add your own
alternative version

Stats

19.7K views
3 bookmarked
Posted 1 Dec 2017
Licenced CPOL

Angular 4: User Authentication using JWT Token

, 1 Dec 2017
Rate this:
Please Sign up or sign in to vote.
User authentication in Angular 4 App using ASP.NET Core JWT Token

Introduction

This is the fourth article of a series of articles on ASP.NET Core Identity:

In the previous post, we created an API controller (TokenController) in our project to generate JWT token and another API controller (GreetingController) which supports bearer authentication scheme. In this article, we will develop an Angular 4 app to implement user authentication based on that API.

I will not go to the details of the Angular app as the internet is full of great Angular tutorials. It's not even worth putting some good Angular tutorial links as better tutorials are popping up everyday.

The complete code for this article is available in the Demo 4 folder in this repo https://github.com/ra1han/aspnet-core-identity.

Preparing the Controllers

The API controllers we created in the previous step are just fine for our Angular app. The only thing that we have to do is add cross origin support as the .NET project and the Angular app is running in different ports.

[EnableCors("CORSPolicy")]
[Route("api/[controller]")]
public class TokenController : Controller
{
.....
.....
}

[EnableCors("CORSPolicy")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
public class GreetingController : Controller
{
.....
.....
}

Preparing the Angular App

We are using Angular 4 for this project.

The project has two components - Login component for the login page and a Home component for showing the greeting message to the authenticated users.

The project also has two services - AuthenticationService to fetch the token based on the provided credentials and UserService which gets the greeting message using the token.

I am also using RxJS to handle the http requests. It is a great tool and I would highly recommend spending some time to learn it well.

The overall project structure looks like this:

Preparing the Authentication Service (authentication.service.ts)

This service has three methods - login, logout and isUserLoggedIn.

The login method sends a post request to the server and gets the jwt token.

login(username: string, password: string): Observable<boolean> {

    var headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=utf-8');

    return this.http.post(
      Constant.ApiRoot + Constant.TokenService,
      { Email: username, Password: password },
      { headers: headers })
      .map((response: Response) => {
        let token = response.json() && response.json().token;
        if (token) {
          this.token = token;
          return true;
        }
        else {
          return false;
        }
      });
  }

Preparing the User Service (user.service.ts)

This service has only one method - getGreeting.

One important thing here is this method accesses the .../api/Greeting end point which is a secured end point. To access it, we have to add the bearer token to the request header.

getGreeting(): Observable<string> {
    let headers = new Headers({ 'Authorization': 'Bearer ' + this.auhenticationService.token });
    let options = new RequestOptions({ headers: headers });

    return this.http.
      get(Constant.ApiRoot + Constant.GreetingService, options).
      map((response: Response) => response.text());
  }

Using the Application

To use the application, first run the .NET application and then run the Angular app. To run the Angular app, just go to the Angular project folder in command prompt and run npm start.

The angular app will load the login page as the user is not logged in.

If we put the credential of an user created in the previous step and hit Login button, the user will be logged in and forwarded to the home page.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Raihan Alam
Software Developer (Senior)
Australia Australia
No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
Questionjwt with external providers Pin
Member 769978624-Oct-18 9:54
memberMember 769978624-Oct-18 9:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.190306.1 | Last Updated 1 Dec 2017
Article Copyright 2017 by Raihan Alam
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid