Simple and fast setup JWT Authentication in the Angular app.

Denis Khrunov
3 min readMay 14, 2022

--

Hello everyone!👋

In this post, I will show you a simple and quick way to set up JWT authentication for an Angular application in six steps.

If you don’t familiar with JWT token based authentication, first read this post.

Last update article: 05.21.2022

Let’s start! 🚀

1️⃣ Install npm dependency @dekh/ngx-jwt-auth into your Angular app:

npm i @dekh/ngx-jwt-auth

Source code of this library here (GitHub).

2️⃣ First, you must to create an Api-service by implementing the BaseAuthApiService base class. This class obliges to implement 3 methods login, logout and refresh method. The login and refresh methods must return an Observable with the value { accessToken: string; refreshToken?: string; }, if your server in the login authorization method and\or in the refresh access token refresh method returns a different format, then it is quite easy to map the value with the map operator from rxjs to the desired format. An example of such a service:

3️⃣ Next, you need to pass the required parameters to the JwtAuthModule.forRoot(options) parameters: authApiService, tokenStorage and authTokenStorage.

  • authApiService: Type<BaseAuthApiService> — A class that implements BaseAuthApiService and makes requests to the server, our previously created auth-api.service.ts class.
  • tokenStorage: Type<BaseTokenStorage> — Storage of regular tokens (not authorization ones).
  • authTokenStorage: Type<BaseTokenStorage> — Storage of authorization tokens.

More information about the available options can be found here.

4️⃣ Provide Interceptor JwtAuthInterceptor:

The JwtAuthInterceptor simply validates the AccessToken before each secure request, if the token is valid, then adds it to the HTTP headers, otherwise tries to update the AccessToken (calls the update method from the AuthApiService) and sends the original request after a successful update.

5️⃣ If in the application we need to get authorization or log out, then we must use the JwtAuthService proxy, which under the hood offers methods from our AuthApiService service, and performs additional actions — saves AccessToken and RefreshToken in storage, updates the authorization status in isLoggedIn$.

Example:

On the authorization form, when sending it, you need to use JwtAuthService and call the login(…args[]: any) method; all arguments passed to this method will be passed to the login(…args[]: any) method our previously created Api-service for authorization AuthApiService (all parameters are passed for each method defined in BaseAuthApiService).

6️⃣ Restrict access to routes that can only be accessed by an authorized user or vice versa only by an unauthorized user.

In the example below, only an unauthorized user can access the /auth/login and /auth/registration pages, and only an authorized user can open the /dashboard page:

Congratulations 🎉, you have configured your application to use 🔐 JWT authentication.

Bonus

List of predefined Token Storages

  • CookiesTokenStorage — abstraction over cookies, saves tokens in cookies;
  • LocalStorageTokenStorage — abstraction over localStorage, stores tokens in localStorage;
  • SessionStorageTokenStorage — abstraction over sessionStorage, saves tokens in sessionStorage;
  • InMemoryTokenStorage — saves tokens in the application memory, there are some drawbacks, when using this storage for authorization tokens, after reloading the page, a request will be made to update the access token (for SPA applications this is not critical), but the most secure storage for authorization tokens;

Creating your own Token Storage

To create your own token storage, you must to inherit and extend the BaseTokenStorage base class and specify in the config yours custom storage of tokens.

You must then define your token store in the JwtAuthModule.forRoot options, or you can define your token store using the TokenStorageRegistry service:

Changing token storage at runtime

In rare cases, you may need to change the token storage at runtime, for this purpose there are two services TokenStorageManager and AuthTokenStorageManager, both of these services implements the same interface. TokenStorageManager is used to manage the storage of simple/non-authorization tokens, and AuthTokenStorageManager is used to manage the storage of authorization tokens.

P.S.

If you find an error, please leave a note or leave a comment.

If this article was helpful to you, clap 👏 , thanks!

--

--

Denis Khrunov
Denis Khrunov

Written by Denis Khrunov

I’m a Front-end Typescript Developer from Russia. I am engaged in front-end development, the main stack of Angular 2+ and in my free time I keep learning.

No responses yet