In this post we’ll go through an example of how to implement JWT authentication with refresh tokens in Angular 9.

The example angular app has just two routes - a login page (/login) and a home page (/). To login the app sends a POST request to the api to authenticate the username and password, on successful login the app receives a JWT token to make authenticated requests to secure api routes, and a refresh token (in a cookie) to get a new JWT token from the api when the old one expires (a.k.a. to refresh the token).

On startup the app attempts to automatically authenticate by sending the refresh token to the api to get a new JWT token, which enables users to stay logged in between page refreshes and browser sessions until they logout. It works by sending the refresh token cookie stored in the browser to the api, if the cookie doesn’t exist or is not valid it will fail silently and the login page will be displayed.

After the user logs in the app starts a countdown to automatically refresh the token one minute before it expires, this is also referred to as “silent refresh” since it happens in the background. The countdown starts again after each silent refresh to keep the user logged in.

The angular app runs with a fake backend by default to enable it to run completely in the browser without a real backend api (backend-less), to switch to a real api you just have to remove or comment out the line below the comment // provider used to create fake backend located in the app module (/src/app/app.module.ts). You can build your own api or hook it up with the ASP.NET Core api or Node.js + MongoDB api available (instructions below).

The example project is available on GitHub at https://github.com/cornflourblue/angular-9-jwt-refresh-tokens.

Here it is in action:

(See on StackBlitz at https://stackblitz.com/edit/angular-9-jwt-refresh-tokens)

#angular 9 #angular #jwt

Angular 9 - JWT Authentication with Refresh Tokens
29.15 GEEK