codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JWT Authentication in Angular

Let’s build an Angular app with JWT authentication.

Changhui Xu
codeburst
Published in
6 min readJul 29, 2020

--

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:

  1. 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.
  2. 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.
  3. Adds an authorization header when sending HTTP requests.
  4. Tracks the expiration time of the access token and sends a request to refresh tokens when the access token is about to expire.
  5. 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…

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Changhui Xu

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.

Responses (5)

Write a response