Angular 8 JWT Authentication with HttpInterceptor and Router
Flow for User Registration and User Login
For JWT Authentication, we’re gonna call 2 endpoints:
POST
api/auth/signupfor User RegistrationPOST
api/auth/signinfor User Login
You can take a look at following flow to have an overview of Requests and Responses that Angular 8 Client will make or receive.

Angular Client must add a JWT to HTTP Authorization Header before sending request to protected resources. This can be done by using HttpInterceptor.
Angular App Diagram with Router and HttpInterceptor
Now look at the diagram below.

– The App component is a container using Router. It gets user token & user information from Browser Session Storage via token-storage.service. Then the navbar now can display based on the user login state & roles.
– Login & Register components have form for submission data (with support of Form Validation). They use token-storage.service for checking state and auth.service for sending signin/signup requests.
– auth.service uses Angular HttpClient ($http service) to make authentication requests.
– every HTTP request by $http service will be inspected and transformed before being sent by auth-interceptor.
– Home component is public for all visitor.
– Profile component get user data from Session Storage.
– BoardUser, BoardModerator, BoardAdmin components will be displayed depending on roles from Session Storage. In these components, we use user.service to get protected resources from API.
Technology
– Angular 8 – RxJS 6
Setup Angular 8 Project
Let’s open cmd and use Angular CLI to create a new Angular Project as following command:
We also need to generate some Components and Services:
After the previous process is done, under src folder, let’s create _helpers folder and auth.interceptor.ts file inside.
Now you can see that our project directory structure looks like this.
Project Structure

Setup App Module
Open app.module.ts, then import FormsModule & HttpClientModule.
We also need to add authInterceptorProviders in providers. I will show you how to define it later on this tutorial.
Create Services
Authentication Service
This service sends signup, login HTTP POST requests to back-end.
_services/auth.service.ts
Token Storage Service
TokenStorageService to manages token and user information (username, email, roles) inside Browser’s Session Storage. For Logout, we only need to clear this Session Storage.
_services/token-storage.service.ts
Data Service
This service provides methods to access public and protected resources.
_services/user.service.ts
You can see that it’s simple because we have HttpInterceptor.
Http Interceptor
HttpInterceptor has intercept() method to inspect and transform HTTP requests before they are sent to server.
AuthInterceptor implements HttpInterceptor. We’re gonna add Authorization header with ‘Bearer’ prefix to the token.
_helpers/auth.interceptor.ts
intercept() gets HTTPRequest object, change it and forward to HttpHandler object’s handle() method. It transforms HTTPRequest object into an Observable<HttpEvents>.
next: HttpHandler object represents the next interceptor in the chain of interceptors. The final ‘next’ in the chain is the Angular HttpClient.
Note: For Node.js Express back-end, please use x-access-token header like this:
Add Bootstrap to Angular project
Open index.html and import Bootstrap inside <head /> tag.
Create Components for Authentication
Register Component
This component binds form data (username, email, password) from template to AuthService.register() method that returns an Observable object.
register/register.component.ts
We use Form Validation in the template:
username: required, minLength=3, maxLength=20email: required, email formatpassword: required, minLength=6
register/register.component.html
Login Component
Login Component also uses AuthService to work with Observable object. Besides that, it calls TokenStorageService methods to check loggedIn status and save Token, User info to Session Storage.
login/login.component.ts
Here are what we validate in the form:
username: requiredpassword: required, minLength=6
login/login.component.html
Create Role-based Components
Public Component
Our Home Component will use UserService to get public resources from back-end.
home/home.component.ts
home/home.component.html
Protected Components
These Components are role-based. But authorization will be processed by back-end.
We only need to call UserService methods:
getUserBoard()
getModeratorBoard()
getAdminBoard()
Here is an example for BoardAdminComponent.
BoardModeratorComponent & BoardUserComponent are similar.
board-admin/board-admin.component.ts
board-admin/board-admin.component.html
App Routing Module
We configure the Routing for our Angular app in app-routing.module.ts.
Routes array is passed to the RouterModule.forRoot() method.
We’re gonna use <router-outlet></router-outlet> directive in the App Component where contains navbar and display Components (corresponding to routes) content.
App Component
This component is the root Component of our Angular application, it defines the root tag: <app-root></app-root> that we use in index.html.
/.component.ts
First, we check isLoggedIn status using TokenStorageService, if it is true, we get user’s roles and set value for showAdminBoard & showModeratorBoard flag. They will control how template navbar displays its items.
The App Component template also has a Logout button link that call logout() method and reload the window.
app.component.html
Run the Angular App
You can run this App with command: ng serve.
This client will work well with the back-end in the post: Spring Boot, MongoDB: JWT Authentication with Spring Security
If you use this front-end app for Node.js Express back-end in one of these tutorials: – Node.js + MySQL: JWT Authentication & Authorization – Node.js + MongoDB: User Authentication & Authorization with JWT
It configures CORS for port 8081, so you have to run command: ng serve --port 8081 instead.
Last updated
Was this helpful?