Policy-Based Authorization with Angular and ASP.NET Core using JWT

In this article, we will create a web application using ASP.NET Core and Angular. We will then implement authentication and policy-based authorization in the application with the help of JWT.

Introduction

 
In this article, we will create a web application using ASP.NET Core and Angular. We will then implement authentication and policy-based authorization in the application with the help of JWT. The web application will have two roles – Admin and User. The application will have role-based access for each role. We will learn how to configure and validate a JWT.
 
At the time of writing the latest stable version for ASP.NET Core is 3.0 and that of Angular is 8.3.
 
Take a look at the final application:
 
Policy-Based Authorization with Angular and ASP.NET Core using JWT
 
Prerequisites
  • Install the latest .NET Core 3.0 SDK here
  • Install the latest version of Visual Studio 2019 here

Source code 

 
Get the source code from GitHub.
 

What is JWT?

 
JWT stands for JSON Web Token. It is an open standard that defines a compact and self-contained way to securely transfer the data between two parties. JWT is digitally signed hence it can be verified and trusted. JWT is recommended to be used in a scenario when we need to implement Authorization or information exchange. To explore JWT in-depth please refer to the official website of JWT.
 

Creating the ASP.NET Core application

 
Open Visual Studio 2019 and click on “Create a new Project”. A “Create a new Project” dialog will open. Select “ASP.NET Core Web Application” and click on Next. Refer to the image shown below.
 
Policy-Based Authorization with Angular and ASP.NET Core using JWT
 
Now you will be at “Configure your new project” screen, provide the name for your application as ngWithJWT and click on create. You will be navigated to “Create a new ASP.NET Core web application” screen. Select “.NET Core” and “ASP.NET Core 3.0” from the dropdowns on the top. Then, select “Angular” project template and click on Create.
 
Refer to the image shown below:
 
Policy-Based Authorization with Angular and ASP.NET Core using JWT
 
This will create our project. The folder structure of our application is shown below:
 
 
The ClientApp folder contains the Angular code for our application. The Controllers folders will contain our API controllers. The angular components are present inside the “ClientApp\src\app” folder. The default template contains a few Angular components. These components won’t affect our application, but for the sake of simplicity, we will delete fetchdata and counter folders from ClientApp/app/components folder. Also, remove the reference for these two components from the app.module.ts file.
 

Adding the Model to the Application

 
Right-click on the project and select Add >> New Folder. Name the folder as Models. Now right-click on the Models folder and select Add >> class. Name the class file as User.cs. This file will contain the User model. Put the following code in this class.
  1. using System;    
  2.     
  3. namespace ngWithJwt.Models    
  4. {    
  5.     public class User    
  6.     {    
  7.         public string UserName { getset; }    
  8.         public string FirstName { getset; }    
  9.         public string Password { getset; }    
  10.         public string UserType { getset; }    
  11.     }    
  12. }     
Similarly, add a new class and name it Policies.cs. This class will define the policies for role-based authorization. Put the following code into it.
  1. using Microsoft.AspNetCore.Authorization;    
  2. using System;    
  3.     
  4. namespace ngWithJwt.Models    
  5. {    
  6.     public static class Policies    
  7.     {    
  8.         public const string Admin = "Admin";    
  9.         public const string User = "User";    
  10.     
  11.         public static AuthorizationPolicy AdminPolicy()    
  12.         {    
  13.             return new AuthorizationPolicyBuilder().RequireAuthenticatedUser().RequireRole(Admin).Build();    
  14.         }    
  15.     
  16.         public static AuthorizationPolicy UserPolicy()    
  17.         {    
  18.             return new AuthorizationPolicyBuilder().RequireAuthenticatedUser().RequireRole(User).Build();    
  19.         }    
  20.     }    
  21. }   
We have also created two policies for authorization. The AdminPolicy method will check for the “Admin” role while validating a request. Similarly, the UserPolicy method will check for the “User” role while validating the request. We will register both of these policies in the ConfigureServices method of Startup.cs file later in this article.
 

Configure appsettings.json

 
Add the following lines to the appsettings,json file.
  1. "Jwt": {    
  2.   "SecretKey""KqcL7s998JrfFHRP",    
  3.   "Issuer""https://localhost:5001/",    
  4.   "Audience""https://localhost:5001/"    
  5. }   
Here we have defined a JSON config for the secret key to be used for encryption. We have also defined the issuer and audience for our JWT. You can use the localhost URL as the value for these properties.
 
Important Note
 
We will be using HmacSha256 as our encryption algorithm for JWT. This algorithm requires a key size of 128 bits or 16 bytes. Hence make sure that your key must satisfy this criterion, otherwise, you will get a run time error.
 

Install NuGet package

 
To configure ASP.NET Core middleware for JWT authentication and authorization we need to install the AspNetCore.Authentication.JwtBearer NuGet package, provided by Microsoft. Navigate to NuGet gallery page for this package. Select the version of .NET Core 3 from the “Version History”. Copy the command from the “package manager” tab. Run this command in the NuGet package manager console of our application. For this application, we are using .NET Core 3.0.0. Therefore, we will run the following command in the package manager console of our application.
  1. Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.0.0  
Refer to the image below.
 
Policy-Based Authorization with Angular and ASP.NET Core using JWT
 

Adding the Login Controller

 
We will add a Login Controller to our application which will handle the Login request from the user. Right-click on the Controllers folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Web from the left panel, then select “API Controller Class” from templates panel and put the name as LoginController.cs. Click on Add. Refer to the image below.
 
Policy-Based Authorization with Angular and ASP.NET Core using JWT
 
Open LoginController.cs file and put the following code into it.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.IdentityModel.Tokens.Jwt;    
  4. using System.Linq;    
  5. using System.Security.Claims;    
  6. using System.Text;    
  7. using Microsoft.AspNetCore.Authorization;    
  8. using Microsoft.AspNetCore.Mvc;    
  9. using Microsoft.Extensions.Configuration;    
  10. using Microsoft.IdentityModel.Tokens;    
  11. using ngWithJwt.Models;    
  12.     
  13. namespace ngWithJwt.Controllers    
  14. {    
  15.     [Produces("application/json")]    
  16.     [Route("api/[controller]")]    
  17.     public class LoginController : Controller    
  18.     {    
  19.         private readonly IConfiguration _config;    
  20.     
  21.         private List<User> appUsers = new List<User>    
  22.         {    
  23.             new User {  FirstName = "Admin",  UserName = "admin", Password = "1234", UserType = "Admin" },    
  24.             new User {  FirstName = "Ankit",  UserName = "ankit", Password = "1234", UserType = "User" }    
  25.         };    
  26.     
  27.         public LoginController(IConfiguration config)    
  28.         {    
  29.             _config = config;    
  30.         }    
  31.     
  32.         [HttpPost]    
  33.         [AllowAnonymous]    
  34.         public IActionResult Login([FromBody]User login)    
  35.         {    
  36.             IActionResult response = Unauthorized();    
  37.             User user = AuthenticateUser(login);    
  38.             if (user != null)    
  39.             {    
  40.                 var tokenString = GenerateJWT(user);    
  41.                 response = Ok(new    
  42.                 {    
  43.                     token = tokenString,    
  44.                     userDetails = user,    
  45.                 });    
  46.             }    
  47.             return response;    
  48.         }    
  49.     
  50.         User AuthenticateUser(User loginCredentials)    
  51.         {    
  52.             User user = appUsers.SingleOrDefault(x => x.UserName == loginCredentials.UserName && x.Password == loginCredentials.Password);    
  53.             return user;    
  54.         }    
  55.     
  56.         string GenerateJWT(User userInfo)    
  57.         {    
  58.             var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"]));    
  59.             var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);    
  60.     
  61.             var claims = new[]    
  62.             {    
  63.                 new Claim(JwtRegisteredClaimNames.Sub, userInfo.UserName),    
  64.                 new Claim("firstName", userInfo.FirstName.ToString()),    
  65.                 new Claim("role",userInfo.UserType),    
  66.                 new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),    
  67.             };    
  68.     
  69.             var token = new JwtSecurityToken(    
  70.                 issuer: _config["Jwt:Issuer"],    
  71.                 audience: _config["Jwt:Audience"],    
  72.                 claims: claims,    
  73.                 expires: DateTime.Now.AddMinutes(30),    
  74.                 signingCredentials: credentials    
  75.             );    
  76.             return new JwtSecurityTokenHandler().WriteToken(token);    
  77.         }    
  78.     }    
  79. }     
Here we have created a list of users called appUsers. We will use this list to verify user credentials. We are using a hard-coded list for simplicity. Ideally, we should store the user credentials in the database and make a DB call to verify the details. The Login method will receive the login details of the user and then verify it by calling the AuthenticateUser method. The AuthenticateUser method will check if the user details exist in the user list appUsers. If the user details exist, then the method will return an object of type User else it will return null. If the user details are verified successfully, we will invoke the GenerateJWT method.
 
The GenerateJWT method will configure the JWT for our application. We are using HmacSha256 as our encryption algorithm. We will also create claims to be sent as payload with our JWT. The claims will contain info about the user such as UserName, FirstName, and UserType. We will use this information on the client app. In the end, we will create the JWT by specifying details such as issuer, audience, claims, expire and signingCredentials. We are setting the expiry time as 30 mins from the time of the creation of token.
 
We will send the JWT token back to the client with an OK response. If the user details are invalid, we will send an Unauthorized response.
 

Configuring Startup.cs file

 
We will configure the request pipeline for the application in the startup.cs file. This will handle the incoming requests for our application. We will add the following code snippet in ConfigureServices method. You can check the full method definition on GitHub.
  1. public void ConfigureServices(IServiceCollection services)    
  2. {    
  3.     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)    
  4.     .AddJwtBearer(options =>    
  5.     {    
  6.         options.RequireHttpsMetadata = false;    
  7.         options.SaveToken = true;    
  8.         options.TokenValidationParameters = new TokenValidationParameters    
  9.         {    
  10.             ValidateIssuer = true,    
  11.             ValidateAudience = true,    
  12.             ValidateLifetime = true,    
  13.             ValidateIssuerSigningKey = true,    
  14.             ValidIssuer = Configuration["Jwt:Issuer"],    
  15.             ValidAudience = Configuration["Jwt:Audience"],    
  16.             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),    
  17.             ClockSkew = TimeSpan.Zero    
  18.         };    
  19.         services.AddCors();    
  20.     });    
  21.     
  22.     services.AddAuthorization(config =>    
  23.     {    
  24.         config.AddPolicy(Policies.Admin, Policies.AdminPolicy());    
  25.         config.AddPolicy(Policies.User, Policies.UserPolicy());    
  26.     });    
  27.     
  28. ...    
  29.   Existing code in the method.    
  30. ..    
  31. }     
We are adding the JWT authentication scheme using the AddAuthentication method. We have provided the parameters to validate the JWT. The description for each parameter is as shown below. 
  • ValidateIssuer = true: It will verify if the issuer data available in JWT is valid.
  • ValidateAudience = true: It will verify if the audience data available in JWT is valid.
  • ValidateLifetime = true: It will verify if the token has expired or not.
  • ValidateIssuerSigningKey = true: It will verify if the signing key is valid and trusted by the server.
  • ValidIssuer: A string value that represents a valid issuer that will be used to check against the token's issuer We will use the same value as we used while generating JWT.
  • ValidAudience: A string value that represents a valid audience that will be used to check against the token's audience. We will use the same value which we used while generating JWT.
  • IssuerSigningKey: The secure key used to sign the JWT.
  • ClockSkew: It will set the clock skew to apply when validating the expiry time.
Important Note 
 
The default value for ClockSkew is 300 seconds i.e. 5 mins. This means that a default value of 5 mins will be added to the expiry time of JWT. E.g. in our case we have set the expiry time as 30 mins but actually it will be 30 + 5 = 35 mins. Hence, we have set the ClockSkew to zero so that the expiry time of JWT will remain the same as we set while generating it.
 
We will register our authorization policies in the ConfigureServices method. The extension method AddAuthorization is used to add authorization policy services. To apply these policies, we will use the Authorize attribute on any controller or endpoint we want to secure.
 
To enable authentication and authorization in our application, we will add the UseAuthentication and UseAuthorization extension methods in the Configure method of Startup class. The code snippet is shown below. You can also check the full method definition on GitHub.
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    
  2. {    
  3.     ...    
  4.     // Existing code    
  5.     ...    
  6.     
  7.     if (!env.IsDevelopment())    
  8.     {    
  9.         app.UseSpaStaticFiles();    
  10.     }    
  11.     app.UseRouting();    
  12.     
  13.     app.UseAuthentication();    
  14.     app.UseAuthorization();    
  15.     
  16.     app.UseEndpoints(endpoints =>    
  17.     {    
  18.         endpoints.MapControllerRoute(    
  19.             name: "default",    
  20.             pattern: "{controller}/{action=Index}/{id?}");    
  21.     });    
  22.         
  23.     ...    
  24.     // Existing code    
  25.     ...    
  26. }    

Adding the User Controller

 
We will add a user controller to handle all user-specific requests. Add a new API controller class, UserController.cs and put the following code into it.
  1. using Microsoft.AspNetCore.Authorization;    
  2. using Microsoft.AspNetCore.Mvc;    
  3. using ngWithJwt.Models;    
  4.     
  5. namespace ngWithJwt.Controllers    
  6. {    
  7.     [Produces("application/json")]    
  8.     [Route("api/[controller]")]    
  9.     public class UserController : Controller    
  10.     {    
  11.         [HttpGet]    
  12.         [Route("GetUserData")]    
  13.         [Authorize(Policy = Policies.User)]    
  14.         public IActionResult GetUserData()    
  15.         {    
  16.             return Ok("This is an normal user");    
  17.         }    
  18.     
  19.         [HttpGet]    
  20.         [Route("GetAdminData")]    
  21.         [Authorize(Policy = Policies.Admin)]    
  22.         public IActionResult GetAdminData()    
  23.         {    
  24.             return Ok("This is an Admin user");    
  25.         }    
  26.     }    
  27. }    
We have defined two methods, one for each role. Both the method will return a simple string to the client. We are using the Authorize attribute with the policy name to implement policy-based authorization to our controller methods.
 

Working on the Client side of the application

 
The code for the client-side is available in the ClientApp folder. We will use Angular CLI to work with the client code.
 
Important Note
 
Using Angular CLI is not mandatory. I am using Angular CLI here as it is user-friendly and easy to use. If you don’t want to use CLI then you can create the files for components and services manually. 
 

Install Angular CLI

 
Open a command window and execute the following command to install angular CLI in your machine.
  1. npm install -g @angular/CLI     
After the Angular CLI is installed successfully, navigate to ngWithJWT\ClientApp folder and open a command window. We will execute all our Angular CLI commands in this window.
 

Create the models

 
Create a folder called models inside the ClientApp\src\app folder. Create a file user.ts in the models folder. Put the following code in it.
  1. export class User {    
  2.     userName: string;    
  3.     firstName: string;    
  4.     isLoggedIn: boolean;    
  5.     role: string;    
  6. }    
Similarly, create another file inside the models folder called roles.ts. This file will contain an enum, which will define roles for our application. Put the following code in it.
  1. export enum UserRole {    
  2.     Admin = 'Admin',    
  3.     User = 'User'    
  4. }     

Create the User Service

 
We will create an Angular service which will convert the Web API response to JSON and pass it to our component. Run the following command.
  1. ng g s services\user  
This command will create a folder with name services and then create the following two files inside it.
  • user.service.ts – the service class file
  • user.service.spec.ts – the unit test file for service
Open user.service.ts file and put the following code inside it.
  1. import { Injectable } from '@angular/core';    
  2. import { HttpClient } from '@angular/common/http';    
  3. import { map } from 'rxjs/operators';    
  4.     
  5. @Injectable({    
  6.   providedIn: 'root'    
  7. })    
  8. export class UserService {    
  9.     
  10.   myAppUrl = '';    
  11.     
  12.   constructor(private http: HttpClient) {    
  13.   }    
  14.     
  15.   getUserData() {    
  16.     return this.http.get('/api/user/GetUserData').pipe(map(result => result));    
  17.   }    
  18.     
  19.   getAdminData() {    
  20.     return this.http.get('/api/user/GetAdminData').pipe(map(result => result));    
  21.   }    
  22. }    
We have defined two methods here to invoke our API endpoints. The method getUserData will invoke the GetUserData method from the User Controller to fetch the user data. The getAdminData method will invoke the GetAdminData method from the User Controller to fetch the Admin data.
 

Create the Auth Service

 
Run the following command to create the auth service.
  1. ng g s services\auth  
Open auth.service.ts and put the following code inside it.
  1. import { Injectable } from '@angular/core';    
  2. import { HttpClient } from '@angular/common/http';    
  3. import { BehaviorSubject } from 'rxjs';    
  4. import { map } from 'rxjs/operators';    
  5. import { Router } from '@angular/router';    
  6. import { User } from '../models/user';    
  7.     
  8. @Injectable({    
  9.   providedIn: 'root'    
  10. })    
  11. export class AuthService {    
  12.     
  13.   userData = new BehaviorSubject<User>(new User());    
  14.     
  15.   constructor(private http: HttpClient, private router: Router) { }    
  16.     
  17.   login(userDetails) {    
  18.     return this.http.post<any>('/api/login', userDetails)    
  19.       .pipe(map(response => {    
  20.         localStorage.setItem('authToken', response.token);    
  21.         this.setUserDetails();    
  22.         return response;    
  23.       }));    
  24.   }    
  25.     
  26.   setUserDetails() {    
  27.     if (localStorage.getItem('authToken')) {    
  28.       const userDetails = new User();    
  29.       const decodeUserDetails = JSON.parse(window.atob(localStorage.getItem('authToken').split('.')[1]));    
  30.     
  31.       userDetails.userName = decodeUserDetails.sub;    
  32.       userDetails.firstName = decodeUserDetails.firstName;    
  33.       userDetails.isLoggedIn = true;    
  34.       userDetails.role = decodeUserDetails.role;    
  35.     
  36.       this.userData.next(userDetails);    
  37.     }    
  38.   }    
  39.     
  40.   logout() {    
  41.     localStorage.removeItem('authToken');    
  42.     this.router.navigate(['/login']);    
  43.     this.userData.next(new User());    
  44.   }    
  45. }    
The login method will invoke the Login API method to validate the user details. If we get an OK response from the API, we will store the JWT in the local storage. The setUserDetails method will extract the payload data from JWT and store it in a BehaviorSubject object called userData. The logout method will clear the local storage and navigate the user back to the login page. It will also reset the userData object.
 

The Login Component

 
Run the following command in the command prompt to create the Login component.
  1. ng g c login --module app  
The “--module” flag will ensure that this component will get registered at app.module.ts. Open login.component.ts and put the following code in it.
  1. import { Component, OnInit } from '@angular/core';    
  2. import { FormGroup, FormBuilder, Validators } from '@angular/forms';    
  3. import { ActivatedRoute, Router } from '@angular/router';    
  4. import { first } from 'rxjs/operators';    
  5. import { AuthService } from '../services/auth.service';    
  6.     
  7. @Component({    
  8.   selector: 'app-login',    
  9.   templateUrl: './login.component.html',    
  10.   styleUrls: ['./login.component.css']    
  11. })    
  12. export class LoginComponent implements OnInit {    
  13.     
  14.   loading = false;    
  15.   loginForm: FormGroup;    
  16.   submitted = false;    
  17.   returnUrl: string;    
  18.     
  19.   constructor(private formBuilder: FormBuilder,    
  20.     private route: ActivatedRoute,    
  21.     private router: Router,    
  22.     private authService: AuthService) { }    
  23.     
  24.   ngOnInit() {    
  25.     this.loginForm = this.formBuilder.group({    
  26.       username: ['', Validators.required],    
  27.       password: ['', Validators.required]    
  28.     });    
  29.   }    
  30.     
  31.   get loginFormControl() { return this.loginForm.controls; }    
  32.     
  33.   onSubmit() {    
  34.     this.submitted = true;    
  35.     if (this.loginForm.invalid) {    
  36.       return;    
  37.     }    
  38.     this.loading = true;    
  39.     const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/';    
  40.     this.authService.login(this.loginForm.value)    
  41.       .pipe(first())    
  42.       .subscribe(    
  43.         () => {    
  44.           this.router.navigate([returnUrl]);    
  45.         },    
  46.         () => {    
  47.           this.loading = false;    
  48.           this.loginForm.reset();    
  49.           this.loginForm.setErrors({    
  50.             invalidLogin: true    
  51.           });    
  52.         });    
  53.   }    
  54. }    
We are setting the required field validation for the login form inside ngOnInit. The loginFormControl method will return the form controls of the login form. We will bind the form control to the input fields of the form in the template file. In the onSubmit method, we are invoking the login method of the AuthService class. Upon successful authentication, we will redirect the user to home page or the returnURL. If the authentication failed, we will reset the form and also set the form error.
 
Open login.component.html and put the following code in it.
  1. <div class="col-md-6 offset-md-3 mt-5">    
  2.   <div *ngIf="loginForm.errors?.invalidLogin" class="alert alert-danger mt-3 mb-0">    
  3.     Username or Password is incorrect.    
  4.   </div>    
  5.   <div class="card">    
  6.     <h5 class="card-header">JWT authentication with Angular and .NET Core 3</h5>    
  7.     <div class="card-body">    
  8.       <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">    
  9.         <div class="form-group">    
  10.           <label for="username">Username</label>    
  11.           <input type="text" formControlName="username" class="form-control" tabindex="1" autofocus    
  12.             [ngClass]="{ 'is-invalid': submitted && loginFormControl.username.errors }" />    
  13.           <div *ngIf="submitted && loginFormControl.username.errors" class="invalid-feedback">    
  14.             <div *ngIf="loginFormControl.username.errors.required">Username is required</div>    
  15.           </div>    
  16.         </div>    
  17.         <div class="form-group">    
  18.           <label for="password">Password</label>    
  19.           <input type="password" formControlName="password" class="form-control" tabindex="2"    
  20.             [ngClass]="{ 'is-invalid': submitted && loginFormControl.password.errors }" />    
  21.           <div *ngIf="submitted && loginFormControl.password.errors" class="invalid-feedback">    
  22.             <div *ngIf="loginFormControl.password.errors.required">Password is required</div>    
  23.           </div>    
  24.         </div>    
  25.         <button [disabled]="loading" class="btn btn-primary">    
  26.           <span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>    
  27.           Login    
  28.         </button>    
  29.       </form>    
  30.     </div>    
  31.   </div>    
  32. </div>    
We are creating a login form having two fields – Username and Password. Both the fields of the form are required fields. The onSubmit method will be called when we click on the Login button. We are using formControlName attribute to bind the input field to the loginForm controls. If the loginForm has invalidLogin error we will display an error message on the screen. We are using Bootstrap for styling the form.
 

The UserHome Component

 
The UserHomeComponent is accessible to the login with roles defined as “user”. Run the command mentioned below to create UserHomeComponent.
  1. ng g c user-home --module app  
Open the user-home.component.ts file and update the UserHomeComponent class by adding the code as shown below.
  1. export class UserHomeComponent implements OnInit {    
  2.     
  3.   userData: string;    
  4.     
  5.   constructor(private userService: UserService) { }    
  6.     
  7.   ngOnInit() {    
  8.   }    
  9.     
  10.   fetchUserData() {    
  11.     this.userService.getUserData().subscribe(    
  12.       (result: string) => {    
  13.         this.userData = result;    
  14.       }    
  15.     );    
  16.   }    
  17. }     
We have defined a method fetchUserData which will invoke the getUserData method of the UserService class. This will return a string and we will store the result in a variable userData of type string.
 
Open the user-home.component.html file and put the following code inside it.
  1. <h2>This is User home page</h2>    
  2. <hr />    
  3. <button class="btn btn-primary" (click)=fetchUserData()>Fetch Data</button>    
  4. <br />    
  5. <br />    
  6. <div>    
  7.     <h4>    
  8.         {{userData}}    
  9.     </h4>    
  10. </div>   
We have defined a button and invoking the fetchUserData on the button click. We are displaying the string value fetched from the API inside a <h4> tag.
 

The Admin-home Component

 
The AdminHomeComponent is accessible to the login with roles defined as “admin”. Run the command mentioned below to create AdminHomeComponent.
  1. ng g c admin-home --module app  
Open the admin-home.component.ts file and update the AdminHomeComponent class by adding the code as shown below.
  1. export class AdminHomeComponent implements OnInit {    
  2.     
  3.   adminData: string;    
  4.     
  5.   constructor(private userService: UserService) { }    
  6.     
  7.   ngOnInit() {    
  8.   }    
  9.     
  10.   fetchAdminData() {    
  11.     this.userService.getAdminData().subscribe(    
  12.       (result: string) => {    
  13.         this.adminData = result;    
  14.       }    
  15.     );    
  16.   }    
  17. }    
We have defined a method fetchAdminData which will invoke the getAdminData method of the UserService class. This will return a string and we will store the result in a variable adminData of type string.
 
Open the admin-home.component.html file and put the following code inside it.
  1. <h2>This is Admin home page</h2>    
  2. <hr />    
  3. <button class="btn btn-primary" (click)=fetchAdminData()>Fetch Data</button>    
  4. <br />    
  5. <br />    
  6. <div>    
  7.     <h4>    
  8.         {{adminData}}    
  9.     </h4>    
  10. </div>   
We have defined a button and invoking the fetchAdminData on the button click. We are displaying the string value fetched from the API inside a <h4> tag. 
 

Adding the links in Nav Menu

 
Open nav-menu.component.ts and update the NavMenuComponent class as shown below.
  1. export class NavMenuComponent {    
  2.   isExpanded = false;    
  3.   userDataSubscription: any;    
  4.   userData = new User();    
  5.   userRole = UserRole;    
  6.     
  7.   constructor(private authService: AuthService) {    
  8.     this.userDataSubscription = this.authService.userData.asObservable().subscribe(data => {    
  9.       this.userData = data;    
  10.     });    
  11.   }    
  12.     
  13.   collapse() {    
  14.     this.isExpanded = false;    
  15.   }    
  16.     
  17.   toggle() {    
  18.     this.isExpanded = !this.isExpanded;    
  19.   }    
  20.     
  21.   logout() {    
  22.     this.authService.logout();    
  23.   }    
  24. }     
We are subscribing to the userData subject of the AuthService class in the constructor and setting the value of a local variable userData. We will use the properties of userData object to toggle the nav-menu links in the template file. The logout method will call the logout method of the AuthService class.
 
We will add the links for our components in the nav menu. Open nav-menu.component.html and remove the links for Counter and Fetch data components and add the following lines.
  1. <li class="nav-item" [routerLinkActive]='["link-active"]'>    
  2.     <a class="nav-link text-dark" *ngIf="!userData.isLoggedIn" [routerLink]='["/login"]'>Login</a>    
  3. </li>    
  4. <li class="nav-item" [routerLinkActive]='["link-active"]'>    
  5.     <a class="nav-link text-dark" *ngIf="userData.isLoggedIn && userData.role==userRole.User" [routerLink]='["/user-home"]' [routerLink]=''>UserHome</a>    
  6. </li>    
  7. <li class="nav-item" [routerLinkActive]='["link-active"]'>    
  8.     <a class="nav-link text-dark" *ngIf="userData.isLoggedIn && userData.role==userRole.Admin" [routerLink]='["/admin-home"]' [routerLink]=''>AdminHome</a>    
  9. </li>    
  10. <li class="nav-item" [routerLinkActive]='["link-active"]'>    
  11.     <a class="nav-link text-dark" *ngIf="userData.isLoggedIn" (click)=logout() [routerLink]=''>Logout</a>    
  12. </li>    
  13. <li class="nav-item" [routerLinkActive]='["link-active"]' *ngIf="userData.isLoggedIn">    
  14.     <a class="nav-link text-dark">Welcome <b>{{userData.firstName}}</b> </a>    
  15. </li>   
Here we are displaying the links for UserHome and AdminHome based on the role of the user. We are also toggling between the Login and Logout button based on the isLoggedIn property of userData object. Clicking on the Login button will navigate the user to the login page whereas clicking on the logout button will invoke the logout method. We will also display the firstName of the user along with a welcome message once the user is authenticated.
 

Securing the routes using route guards

 
To protect URL routes from unauthorized access we will create route guards. We will create two guards for protecting user routs and admin routes.
 
Run the following commands to create an admin guard.
  1. ng g g guards/admin --implements CanActivate   
Here we are specifying the interfaces to implement using the implements flag. This command will create a folder name guards and add two files admin.guard.ts and admin.guard.spec.ts. Open admin.guard.ts file and put the following code inside it.
  1. import { Injectable } from '@angular/core';    
  2. import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';    
  3. import { Observable } from 'rxjs';    
  4. import { AuthService } from '../services/auth.service';    
  5. import { User } from '../models/user';    
  6. import { UserRole } from '../models/roles';    
  7.     
  8. @Injectable({    
  9.   providedIn: 'root'    
  10. })    
  11. export class AdminGuard implements CanActivate {    
  12.   userDataSubscription: any;    
  13.   userData = new User();    
  14.   constructor(private router: Router, private authService: AuthService) {    
  15.     this.userDataSubscription = this.authService.userData.asObservable().subscribe(data => {    
  16.       this.userData = data;    
  17.     });    
  18.   }    
  19.     
  20.   canActivate(    
  21.     next: ActivatedRouteSnapshot,    
  22.     state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {    
  23.     
  24.     if (this.userData.role === UserRole.Admin) {    
  25.       return true;    
  26.     }    
  27.     
  28.     this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });    
  29.     return false;    
  30.   }    
  31. }   
We will subscribe to userData subject in the constructor of the AdminGuard class. We will override the canActivate method of the interface CanActivate. This method will return true if the user role is Admin otherwise it will set the returnUrl and navigate to the login page.
 
Similarly, we will create another guard to protect user routes. Run the command shown below.
  1. ng g g guards/auth --implements CanActivate  
Open auth.guard.ts file and put the following code inside it.
  1. import { Injectable } from '@angular/core';    
  2. import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';    
  3. import { Observable } from 'rxjs';    
  4. import { AuthService } from '../services/auth.service';    
  5. import { User } from '../models/user';    
  6. import { UserRole } from '../models/roles';    
  7.     
  8. @Injectable({    
  9.   providedIn: 'root'    
  10. })    
  11. export class AuthGuard implements CanActivate {    
  12.   userDataSubscription: any;    
  13.   userData = new User();    
  14.   constructor(private router: Router, private authService: AuthService) {    
  15.     this.userDataSubscription = this.authService.userData.asObservable().subscribe(data => {    
  16.       this.userData = data;    
  17.     });    
  18.   }    
  19.   canActivate(    
  20.     next: ActivatedRouteSnapshot,    
  21.     state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {    
  22.     
  23.     if (this.userData.role == UserRole.User) {    
  24.       return true;    
  25.     }    
  26.     
  27.     this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });    
  28.     return false;    
  29.   }    
  30. }    
This guard is similar to the AdminGuard. We will verify if the user role is User then return true else set the returnUrl and navigate to the login page.
 

Add HTTP Interceptor

 
We will create an HTTP interceptor service to send the authorization token in the header of each API request. This will make sure that only the authorized user can access a particular API. Run the command shown below to create “HttpInterceptorService”.
  1. ng g s services\http-interceptor
Open the http-interceptor.service.ts file and put the following code inside it.
  1. import { Injectable } from '@angular/core';    
  2. import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';    
  3. import { Observable } from 'rxjs';    
  4.     
  5. @Injectable({    
  6.   providedIn: 'root'    
  7. })    
  8. export class HttpInterceptorService implements HttpInterceptor {    
  9.   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    
  10.     const token = localStorage.getItem('authToken');    
  11.     if (token) {    
  12.       request = request.clone({    
  13.         setHeaders: {    
  14.           Authorization: `Bearer ${token}`,    
  15.         }    
  16.       });    
  17.     }    
  18.     return next.handle(request)    
  19.   }    
  20. }     
The HttpInterceptorService class will implement the HttpInterceptor interface and override the intercept method. Inside this method, we will fetch the JWT from the localStorage. If the token exists we will modify the request header of the API call by assigning the token value to the Authorization property of headers.
 

Add Error Interceptor

 
We will add an error interceptor to intercept and handle the errors gracefully. This will make sure that the user experience is not hampered in case of any error from the server.
 
Run the command shown below to create “ErrorInterceptorService”.
  1. ng g s services\error-interceptor
Open the error-interceptor.service.ts file and put the following code inside it.
  1. import { Injectable } from '@angular/core';    
  2. import { AuthService } from './auth.service';    
  3. import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';    
  4. import { Observable, throwError } from 'rxjs';    
  5. import { catchError } from 'rxjs/operators';    
  6.     
  7. @Injectable({    
  8.   providedIn: 'root'    
  9. })    
  10. export class ErrorInterceptorService implements HttpInterceptor {    
  11.     
  12.   constructor(private authService: AuthService) { }    
  13.     
  14.   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    
  15.     return next.handle(request).pipe(catchError(err => {    
  16.       if (err.status === 401) {    
  17.         this.authService.logout();    
  18.       }    
  19.       return throwError(err.status);    
  20.     }));    
  21.   }    
  22. }   
This is similar to HttpInterceptorService. We will implement the HttpInterceptor interface and inside the intercept method, we will catch the error from HttpRequest. If we get HTTP error code as 401 i.e. unauthorized from the server, we will invoke the logout method for that user.
 
Important Note
In a real-world scenario, we should implement the refresh token feature upon getting an unauthorized error from the server. This will make sure that the user doesn’t get logged out frequently. Implementing refresh token on JWT is beyond the scope of this article but I will try to cover it in future article.
 

Update App component

 
Open app.component.ts file and add update the AppComponent class as shown below. This will make sure that the logged-in user data won't be lost on page reload.
  1. export class AppComponent {    
  2.   constructor(private authService: AuthService) {    
  3.     if (localStorage.getItem('authToken')) {    
  4.       this.authService.setUserDetails();    
  5.     }    
  6.   }    
  7. }     

Update App module

 
At last, we will update the app.module.ts file by adding routes for our components and applying auth guards to the routes. We will also add our interceptors in the “providers” array. Update the app.module.ts file as shown below. You can refer to the GitHub for the complete code of this file.
  1. imports: [    
  2. BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),    
  3. HttpClientModule,    
  4. FormsModule,    
  5. ReactiveFormsModule,    
  6. RouterModule.forRoot([    
  7.   { path: '', component: HomeComponent, pathMatch: 'full' },    
  8.   { path: 'login', component: LoginComponent },    
  9.   { path: 'user-home', component: UserHomeComponent, canActivate: [AuthGuard] },    
  10.   { path: 'admin-home', component: AdminHomeComponent, canActivate: [AdminGuard] }    
  11. ])    
  12. ],    
  13. providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true },    
  14. { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptorService, multi: true },    
  15. ],    
  16. bootstrap: [AppComponent]    

Execution Demo

 
Launch the application by pressing F5 from Visual Studio. You can perform the authentication and authorization as shown in the GIF below.

Policy-Based Authorization with Angular and ASP.NET Core using JWT

 

Summary

 
We have created an ASP.NET Core application and configured JWT authentication for it. We learned how JWT is configured and validated on the server. The application also has policy-based authorization. We defined two roles for our application and provided role-based access for each role. The client app is created using Angular. We also implemented interceptors for our client to send authorization token in the headers and to handle any error response coming from the server. 
 
Please get the source code from GitHub and play around for a better understanding. You can also read my other articles on my blog.
 
See Also