Member-only story
JWT Authentication in Angular
Let’s build an Angular app with JWT authentication.

In my last article, JWT Auth in ASP.NET Core, we talked about the implementation of JWT in the back-end. To follow up, this article will focus on the front-end part of the JWT story. You can find the front-end source code from the same GitHub repository as the back-end part.
To make JWT authentication work, the front-end application at least operates in the following scenes:
- Displays a login form, and sends user credentials to the back-end service to get user’s claims, a JWT access token, and a refresh token.
- Stores the JWT access token and refresh token in a browser’s localStorage, so that the application in different browser tabs can use the same tokens.
- Adds an authorization header when sending HTTP requests.
- Tracks the expiration time of the access token and sends a request to refresh tokens when the access token is about to expire.
- Removes the tokens from localStorage when the user logs out.
Today, we will build a simple app using Angular. We will implement an AuthService
class to handle login, logout, and refresh token processes, as well as operations for localStorage key-value pairs. We will create a JwtInterceptor
class to add a JWT Bearer token to the HTTP request headers, and an UnauthorizedInterceptor
class to redirect the user to the login page if an HTTP status code 401 is received. We will use an AuthGuard
to prevent unauthenticated users from visiting the application pages.
If you pull the code from my GitHub repository, then you can run the demo application on Linux Docker containers. Or, if you want, you can run the Angular app and the ASP.NET Core app separately. The following screen recording shows a demo of this app.

Now let’s dive into the code.
auth.service.ts
Let’s use Angular CLI to generate an auth.service.ts
file. I find that this AuthService
class is a little bit lengthy, so I have decided to first paste the…