Click here to Skip to main content
15,180,555 members
Articles / Programming Languages / C#
Posted 1 Dec 2017


7 bookmarked

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
User authentication in Angular 4 App using ASP.NET Core JWT Token


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

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.

public class TokenController : Controller

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
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.

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

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

      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.

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


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


About the Author

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

Comments and Discussions

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