Angular is a modern framework for developing single-page web applications. Angular is developed and backed by Google. Back in days creating the single-page applications was a nightmare for developers. We had to manage everything from the state management to the HTTP calls.

But those days are definitely gone.

Now we have plenty of JavaScript frameworks available on the market, ready for the development process of theĀ amazing web applications. Angular is one of those frameworks. It’s both a popular and feature-rich framework that you can get to know and work with easily.

Creating a rich browser application is awesome but implementing the security is equally important if not even more.

In this article, we are going to learn how we can implement authentication and authorization in Angular. We are going to see how we can securely transfer the userā€™s credentials from a browser to a server and vice versa.

VIDEO: ASP.NET Core Authentication with JWT and Angular - Part 2.

This part is the continuation of the previous part where we have covered the JWT authentication backend side. In this part, we are going to consume that Web API in our Angular application. Furthermore, in the next article, we are going to learn how to refresh the token generated from our API.

You can download the source code for the starting projectsĀ here and for the finished projects here.

This blog is divided into the following sections:

Enabling Cross-Origin Requests (CORS)

By default, you canā€™t send an AJAX request over HTTP to servers on a different origin due toĀ browser’s security concerns. The HTTP protocol is not a secure protocol as it sends the requests in the plain text (at least HTTP v1 does) and anyone can potentially use a web proxy software to intercept modify the request.

On the other hand, the HTTPS protocol is a secure way to transfer information, and some browsers by default allow requests to cross-origin servers on HTTPS.

So, what can we do?

We need to configure the server to receive cross-origin requests. By default, the ASP.NET Core application will reject any request coming from theĀ cross-origin clients. To enable CORS in .NET Core Web API, we need to implement a middleware in the Configure method of theĀ Startup class.

Let’s open the webapplication-start project (you may find it in here) andĀ add the code to theĀ ConfigureServicesĀ method to configure the CORS policy:

services.AddCors(options =>
    options.AddPolicy("EnableCORS", builder =>

To make this middleware available forĀ the application, addĀ the following code in the Configure method:

We can find out more about CORS and the additional options to configure it on this location: Enabling CORS in ASP.NET Core.


At this point, the server is ready to listen to the cross-origin requests.

Implementing Login

We have created the Angular starter application (available for download from here) which contains all the necessary code (basic Angular components, the routes, and basic form validation) we need for this post. With this project, it is going to be much easier for us to follow along with this post, because we can focus only on the parts important for the JWT authentication. To find out in detail how to work with Angular, visit our Angular Series.

Let’s download the starter Angular application, so we could easily follow all the coding parts.

To implementĀ the login, we are going to create theĀ login method in theĀ LoginComponent. Inside the login method, we are going to collect the username and the password from the login form. When a user presses the login button, we are going to collect the user’s credentials with the Angular event binding.

Once we have the credentials, we are going to send them to the server viaĀ the HTTP POST request to the login endpoint. The server is going to validate the data. If the username and password are valid, the server will issue a JSON web token and send it back to the browser.

A valid username is “johndoe” and the valid password is “[email protected]“, as you can read in part 1 of the JWT series.

Ā Let’s implement the login method:

login(form: NgForm) {
    const credentials = JSON.stringify(form.value);"http://localhost:5000/api/auth/login", credentials, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
    }).subscribe(response => {
      const token = (<any>response).token;
      localStorage.setItem("jwt", token);
      this.invalidLogin = false;
    }, err => {
      this.invalidLogin = true;

InĀ the code above, we sendĀ the HTTP POST request towards the server, by using an HttpClient service defined in the@angular/common/httpĀ module. The HttpClient service exposes some helper methods equivalent to HTTP verbs. For example, if we needĀ to send the HTTPĀ POST request to the server, we have the post method inĀ the HttpClient service. The call to each method returns an Observable which is a JavaScript way of makingĀ the asynchronous calls.

The Observable Callbacks

The Observable provides three callbacks for us toĀ subscribe to while waiting for the response. The first callback is called when Observable receives a successful response. The second callback is called when there is an error. The third callback is called whether there is a response or an error, it’s a way of signaling that the request is completed.

In the response callback, we get the token from the server and we save the token inĀ the browserā€™s local storage. The browser’s local storage is a collection ofĀ the key-value pairs that browser stores per website.

Once we have the token persisted in storage, we can use it for future calls to accessĀ the protected resources on theĀ server. You can think of a token as a special identity card that you may use to access the secret resources in your organization.

Let’s continue with the login form implementation in theĀ login.component.htmlĀ file:

<form class="form-signin" #loginForm="ngForm" (ngSubmit)="login(loginForm)">
  <div class="container-fluid">
    <h2 class="form-signin-heading">Login</h2>
    <div *ngIf="invalidLogin" class="alert alert-danger">Invalid username or password.</div>
    <label for="username" class="sr-only">Email address</label>
    <input type="email" id="username" name="username" ngModel class="form-control" placeholder="User Name" required autofocus>
    <label for="password" class="sr-only">Password</label>
    <input type="password" id="password" name="password" ngModel class="form-control" placeholder="Password" required>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>

Implementing Logout

Implementing the logout function is very simple. Itā€™s similar to losing the identity card. If we donā€™t have the card, we are not able to access the secretly protected resources. To log out the user, we are simply going to delete the token stored in the local storage which is the only key to access protected resources.

If we donā€™t have the token, the server simply doesnā€™t know our identity and it’s going to reject our calls to the protected resources. To implement log out we are going to createĀ theĀ logout method inĀ theĀ HomeComponent. Inside the logout method, we are going to remove the token fromĀ the local storage and thatā€™s all.

logOut() {

To perform the logout, we need to press the log out link on the Home page.

So far so good.

At this point our logout functionality is complete.

Installing Angular Jwt Library

To install theĀ angular2-jwtĀ library, let’s run the following command in the terminal window:

npm install @auth0/[email protected]

This library is going to help us work with the jwt token in Angular. Let’s configure it by modifying the app.module.ts file:
import { AuthGuard } from './guards/auth-guard.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { JwtModule } from "@auth0/angular-jwt";

import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { CustomersComponent } from './customers/customers.component';
import { AppComponent } from './app.component';

export function tokenGetter() {
  return localStorage.getItem("jwt");

  declarations: [
  imports: [
      { path: '', component: HomeComponent },
      { path: 'login', component: LoginComponent },
      { path: 'customers', component: CustomersComponent },
      config: {
        tokenGetter: tokenGetter,
        whitelistedDomains: ["localhost:5000"],
        blacklistedRoutes: []
  providers: [AuthGuard],
  bootstrap: [AppComponent]
export class AppModule { }

We inject the JwtModule and configure it to use the tokenGetter function to retrieve the token from the local storage and to include it into any Http request executed by the HttpClientModule.

Additionally, we add the servers URI in the white domain list required by JwtModule.

For additional information about this library, you can visit @auth0/angular-jwt.

Protecting Angular Routes

Protecting the Angular routes is the crucial part of implementing security in the Angular application. To protect the routes, Angular provides theĀ CanActivate interface. This interface exposes theĀ canActivateĀ method which we can implement to provide a route guard.Ā TheĀ canActivate methodĀ triggers before the Angular route activates, it acts as a guard toĀ the Angular routes. Inside the canActivate method, we can write any custom logic to protect our routes.

In the folder named guards, we can find the auth-guard.service.ts file. Let’s implement theĀ AuthGuard logic which provides a custom implementation of theĀ CanActivate interface:

export class AuthGuard implements CanActivate {
  constructor(private jwtHelper: JwtHelperService, private router: Router) {
  canActivate() {
    const token = localStorage.getItem("jwt");

    if (token && !this.jwtHelper.isTokenExpired(token)){
      return true;
    return false;

Inside the canActivate method, we are going to check if the token expired. To check the validity of a token, we are using theĀ JwtHelper service. The JwtHelper service is defined in the @auth0-angular-jwtĀ library which is a lightweight library that provides some helper services to easily work with JSON web tokens in Angular.

Now, we are going to applyĀ theĀ AuthGuard service toĀ theĀ CustomersComponent route inĀ theĀ AppModule.Ā To applyĀ theĀ AuthGuard, we simply provide the service name inĀ theĀ CustomersComponent‘s route object by using thecanActivate attribute.

Following is the code snippet to activate theĀ AuthGuardservice for theĀ CustomerComponent route inĀ theĀ app.module.ts file:

      { path: '', component: HomeComponent },
      { path: 'login', component: LoginComponent },
      { path: 'customers', component: CustomersComponent, canActivate: [AuthGuard] },

The canActivate property in theĀ Route object is an array. That means you can specify more than one service.

Before we continue, let’s add a few changes to the home.component.ts file:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { JwtHelperService } from '@auth0/angular-jwt';

  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: []
export class HomeComponent {

  constructor(private jwtHelper: JwtHelperService, private router: Router) {}

  isUserAuthenticated() {
    const token: string = localStorage.getItem("jwt");
    if (token && !this.jwtHelper.isTokenExpired(token)) {
      return true;
    else {
      return false;

  public logOut = () => {

We have added an additional check for the login/logout buttons.

Accessing Protected Resources

To access the protected resources we need to send theĀ JWT token in the Authorization header with each request. The server is going to verify the token and grant access to protected resources.

In our CustomerComponent, on the component initialization, we are going to send a request to the server to access a list of customers.

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

  selector: 'app-customers',
  templateUrl: './customers.component.html',
  styles: [``]
export class CustomersComponent implements OnInit  {
  customers: any;
  constructor(private http: HttpClient) { }
  ngOnInit() {
    this.http.get("http://localhost:5000/api/customers", {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
    }).subscribe(response => {
      this.customers = response;
    }, err => {

In the code snippet above, we are sending an HTTP GET request to the endpoint http://localhost:5000/api/customers with the JSON web token in the Authorization header. Yes, you can’t see the authorization header in the request but it will be there due to the auth-jwt library configuration:

authorization header

If the token is invalid the server is going to reply with the 401 Unauthorized response. If the token is valid, then we are going to see a list of customers.

The token can expire as well, and to learn how to refresh it, you can read the part 3 of the JWT series.

Role-Based Authorization

Right now, we have a fully functional application (the backend and the frontend part) which uses the JWT features for the user authentication. But, because we have only theĀ [Authorize] attribute on top of the Customers controller’s GET action, all the authenticated users have access to that endpoint.

What if we don’t want this type of behavior? What if we want only Managers to have access to that endpoint?

Well, to accomplish that, we need to make a couple of changes to our Web API part.

First, let’s modify the [Authorize]attribute to give access only to a user with the Manager role:

[HttpGet,Authorize(Roles = "Manager")]
public IEnumerable<string> Get()
    return new string[] { "John Doe", "Jane Doe" };


Additionally, let’s modify the Login method in the AuthController to set up the user claims:

[HttpPost, Route("login")]
public IActionResult Login([FromBody]LoginModel user)
    if (user == null)
        return BadRequest("Invalid client request");

    if (user.UserName == "johndoe" && user.Password == "[email protected]")
        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("[email protected]"));

        var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

        var claims = new List<Claim>
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.Role, "Manager")

         var tokeOptions = new JwtSecurityToken(
            issuer: "http://localhost:5000",
            audience: "http://localhost:5000",
            claims: claims,
            expires: DateTime.Now.AddMinutes(5),
            signingCredentials: signinCredentials

        var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
        return Ok(new { Token = tokenString });
        return Unauthorized();

In the changed parts of the code, we create claims by adding the username and the role claim to the Claim list. Now, our “johndoe” user is a Manager and it should have access to the Customer’s GET action. These claims are going to be included in our token. If we try to login with the Angular application, everything should work as before without any problems.

All the JWT related logic is inside our Login method for the sake of simplicity. But we encourage you to create a new class (JwtConfigurator or use any other name) and transfer all the SymmetricSecurityKey, SigninCredentials, Claims, and JWtSecurityToken logic to a new class.

Finally, let’s check what is going to happen if the “johndoe” has the Operator role and not the Manager role. To simulate this, we need to modify the role claim from the Manager to the Operator:

var claims = new List<Claim>
     new Claim(ClaimTypes.Name, user.UserName),
     new Claim(ClaimTypes.Role, "Operator")

Now, we still are able to log in but once we try to access the Customer’s GET action, we are going to get the 403 Forbidden response:

jwt-forbidden in Angular JWT

Awesome, our authorization part works like a charm.

JwtHelper DecodeToken

One more thing though. Let’s see how we can extract the data from the token on the client side.

The jwtHelper service has the decodeToken function which can decode our token into the JSON object. Because we have already injected the JwtHelper service into the AuthGuard service, let’s modify that service a bit just to see how the decodeToken function works. We are going to add one line of code that checks if the token exists and if it hasn’t expired:

if (token && !this.jwtHelper.isTokenExpired(token)){
  return true;

Here is the result:
{ "johndoe", "Manager", 
  exp: 1525510870, 
  iss: "http://localhost:5000", 
  aud: "http://localhost:5000"


By reading this post you have learned:

  • How to configure cross-origin requests in the browser and on server
  • To login users in AngularStore save JWT in local storage.
  • How to remove JWT from local storage and how to log out a user in Angular
  • To protect Angular routes with theĀ CanActivateĀ interface
  • How to access protected resources on the server by sending tokens in the Authorization header

In the next article, we are going to learn about Refreshing Tokens in Web Applications.