Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

Angular 4: User Authentication using JWT Token

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
1 Dec 2017CPOL2 min read 29.8K   7   2
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.

çs
[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:

Image 1

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.

JavaScript
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.

JavaScript
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.

Image 2

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.

Image 3

License

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


Written By
Software Developer (Senior)
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGreat read Pin
rammanusani26-Mar-19 8:12
rammanusani26-Mar-19 8:12 
Questionjwt with external providers Pin
Member 769978624-Oct-18 9:54
Member 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.