avatarFuji Nguyen

Summary

The undefined website provides a comprehensive tutorial on implementing Role-Based Access Control (RBAC) using JSON Web Tokens (JWT) in Angular applications, complete with code examples, design considerations, and a GitHub repository for further exploration.

Abstract

The undefined website delves into the intricacies of securing Angular applications using RBAC, leveraging JWT for authentication and authorization. The tutorial, authored by Fuji Nguyen, builds upon the Angular 12 Starter Kit available on GitHub, which includes UI/UX Bootstrap, server-side pagination, sort, filter, and CRUD operations. It covers the design and implementation of RBAC, the use of JWT to secure Angular SPAs, and the integration of role claims within JWT to manage user access levels. The article emphasizes the importance of separating authentication and authorization concerns by implementing distinct AuthGuard and RoleGuard services. It also provides a step-by-step code walk-through, practical examples, and references to online resources and related tutorials, including a link to the complete source code for an online demo. The tutorial aims to equip developers with the knowledge and tools to enforce role-based menu access and content security within their Angular applications effectively.

Opinions

  • The author, Fuji Nguyen, acknowledges the importance of crediting high-quality open-source projects and online resources that contributed to the development of the tutorial.
  • The tutorial is designed to be practical and hands-on, with a strong emphasis on real-world application through the use of a demonstrable online example and complete source code.
  • The author suggests that the single-responsibility principle (SRP) is crucial in architecting guards for authentication and authorization in Angular applications.
  • Fuji Nguyen encourages readers to engage with the content by following him on Medium and becoming a member for more in-depth articles, indicating a commitment to ongoing educational content creation.
  • The author promotes an AI service, ZAI.chat, as a cost-effective alternative to ChatGPT Plus (GPT-4), highlighting its affordability and similar capabilities.

Angular Guard for Role-Based Access Control (RBAC) Driven by JWT

Photo by Matheus Ferrero on Unsplash

Introduction

In June 2021, I released the Angular 12 Starter Kit on GitHub with boilerplate code for UI/UX Bootstrap, server-side pagination, sort, filter, and CRUD. The Angular app is secured by JSON Web Token (JWT) to facilitate authentication and authorization. This story will do a deep dive into the implementation of Role-Based Access Control (RBAC) using role claims available in the JWT.

Online Resources Highlights

credit where credit’s due

To develop this tutorial, I have reviewed and integrated tools and techniques from the following high-quality opensource projects and online resources.

  1. manfredsteyer/angular-oauth2-oidc — this opensource project has 1.4K stars on GitHub. It is a NPM package supporting OpenId Connect (OIDC) and OAuth 2 and in Angular. The library provides developer-friendly methods to work with JWT.
  2. Angular Role-Based Routing Access with Angular Guard — this Medium publication from Erkan Güzeler is an excellent reference to the Angular Guard concept and coding.

RBAC Overview

Role-based access control (RBAC) limits application access based on the user’s roles within an organization or company. The role in RBAC typically refers to the levels of access that users have to the application. To better understand RBAC, imagine that you work on an Angular app to manage company Employee Profiles. There are three roles in the app

  1. Employee — users in this role can view and update their own profile
  2. Manager — users in this role can view the profile of their subordinators and approve profile changes
  3. HR Admin — users in this role can enroll new employees and make administrative edit

Figure 1 is a screenshot of a demo app where the Employee, Manager, and Admin menus are protected by Employee, Manager, and HR Admin application roles respectively. You can try the online demo using the accounts below.

  1. (antoinette16, Pa$$word123) — has Employee role and can access Employee page
  2. (rosamond33, Pa$$word123) — has Employee and Manager roles and can access the Employee and Manager pages
  3. (ashtyn1, Pa$$word123) — has Employee, Manager, and HR Admin roles and can access the Employee, Manager, and Admin pages

In this tutorial, we will learn the in and out of implementing the RBAC in Angular. When it is appropriate, I will link to GitHub so you can find the source code files.

Figure 1 — Example app with menu protected by user’s roles

Screencast

The complementary Youtube video is a record of my desktop going over the user interface navigation of the online demo. It will help to get you familiar with the use of role-based access to secure the menu items. Background music is coming (:

Prerequisites

The following tools and skills are recommended.

  1. Familiar with OIDC, oAuth2 and JWT
  2. Familiar with Angular Router

Tutorial Content

The tutorial will provide

  1. An overview of JWT to secure Angular
  2. The design and implementation of RBAC
  3. Code walk-thru

Overview of JWT in Angular app

In the Angular SPA application, when the users successfully log in using their credentials, a JWT will be saved locally in the browser, typically in local or session storage. In Chrome developer tools, developers can see the JWT from the Application tab. Figure 2 depicts an example of JWT in Local Storage.

Figure 2— Example of JWT in the Local Storage in Chrome > Developer Tools > Application tab

When the users want to access a protected WebAPI resource, the Angular app will retrieve the JWT access_token from local storage and sends the access_token in the Authorization header using the Bearer schema. The user’s roles must be included in the access_token, so the backend API can verify access based on roles. Figure 3 is an example of the decoded Access token in jwt.ms where you can see the role claims.

Figure 3— Example of the roles in access_token

Design Consideration

The design for Angular guard supports three access types

  1. Anonymous — this access is usually set for public accessible pages, where the identity of the individual visiting the site is not important.
  2. Authenticated — this access encompasses all users who have logged in with a username and password or multi-factor authentication.
  3. Authorized — this access gives users permission to access a resource based on claims such as roles in the JWT.

Implementation

Architecting a separate guard for authentication and authorization is the approach to reinforce the single-responsibility principle (SRP). The implementation consists of two guard files

  1. auth-guard.service.ts — this file implements AuthGuard class to check for authentication based on the user’s login
  2. role-guard.service.ts this file implements RoleGuard class to check for authorization based on roles.

For routes that need Anonymous access such as Home page, the canActivate is NOT specified in the home-routing.module.ts. See Figure 4 for a screenshot of the example code in the home path.

Figure 4— Example of the Home route where the canActivate is not specified

For routes that need Authenticated (login) access such as Position and Position Detail pages, the canActivate is specified in the position-routing.module.ts. See Figure 5 for a screenshot of the example code in the detail path where AuthGuard is referenced in canActivate attribute.

Figure 5 — Example route using AuthGuard

For routes that require Authorization access (RBAC) such as Employee, Manager, and Admin pages, the canActivate includes both AuthGuard and RoleGuard. For example, in the employee-routing.module.ts, the AuthGuard and RoleGuard are both specified in canActivate attribute. In addition, the role is passed via the data attribute with the value Employee. See Figure 6 for a screenshot of the example code in the detail path.

Figure 6 — Example source code where canActivate include both AuthGuard and RoleGuard

Code Walk-Thru of AuthGuard

Figure 7 is the source code listing of auth-guard.service.ts

Line 15: call the OIDC JS library to check the login status

Line 20: activate toaster to alert the user if failed login

Line 27–30: display toaster to alert the user to log in

Code Walk-Thru of RoleGuard

Figure 8 is the source code listing of role-guard.service.ts

Line 14: call the OIDC JS library to check the login status

Line 19: check roles that exist in the data of the route

Line 22–23: call OIDC JS library to retrieve login profile and roles

Line 26: compare login user’s role vs route’s required roles

Line 31: display toaster to alert the user of requiring role to access

Line 42–48: routine to display toaster

Related Tutorials

The following tutorials are related to this story. Tutorial #1 below has the complete source code of the online demo referenced in this story. Enjoy!

  1. Angular Starter Kit for Rapid Prototype — Angular 12 starter repo with boilerplate code for server-side pagination, CRUD, OIDC/oAuth2 JWT login, role-based access, and UI/UX Bootstrap. Include ASP.NET CORE 5 source code for the backend Token Service Server and REST Api Resources.
  2. ASP.NET Core Token Service Starter Kit — Ready-to-serve middleware ASP.NET CORE Token Service Starter Kit to secure SPA applications written in Angular, React, or Blazor WASM
  3. ASP.NET Core REST API Template Starter Kit — Recipe for building advanced REST API (microservice)
  4. Secure Angular 11/12 with JWT and IdentityServer4 Admin UI — In JWT we trust

GitHub Source Code

The repository referenced in this tutorial is below.

Summary

This story provides a tutorial on how to leverage role claims in the JWT to support RBAC. If you look for a robust solution to secure content on any given page using expanded permissions beyond roles, check out my post on Reddit where you find discussions on the opensource module ngx-permissions.

Thanks for reading! Hope you found it useful. Want more? Please follow me and become a member on medium for more articles. With your support, I’ll keep creating awesome content for you. Have a great day ahead! — Fuji Nguyen

Angular
Rbac
Jwt
Toasters
Recommended from ReadMedium