Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Angular 4: User Authentication using JWT Token

0.00/5 (No votes)
1 Dec 2017 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here