Urgent.News

What's breaking now, across thousands of outlets.

Tech

Handling JWT Authentication & Refresh Tokens in Angular Using an HTTP Interceptor

While working on authentication in Angular, one thing I found particularly useful was using an HTTP interceptor to handle authentication automatically. Instead of manually adding the access token to every API request, the interceptor can: Attach the JWT access token to outgoing requests Detect 401 Unauthorized responses Use the refresh token to obtain a new access token Retry the failed request…

When working with authentication in Angular, an HTTP interceptor proves to be a valuable tool for handling authentication automatically. This interceptor attaches the JWT access token to outgoing requests, detects 401 Unauthorized responses, uses the refresh token to obtain new access tokens, retries failed requests, and logs out the user if the refresh token is expired or invalid.

To implement this, first, retrieve the authentication data from localStorage using the `getAuth` function. If an access token exists, clone the request and add the Authorization header, setting it to `Bearer ${auth.accessToken}`.

Handling 401 Unauthorized responses involves checking if the error status is 401 and a refresh token is available. If so, call the refresh-token endpoint using `authService.refreshToken()`. Upon receiving the new tokens, store them and create a new version of the original request with the new access token. Retry the failed request by calling `next(retryReq)`.

If the refresh request fails, the `catchError` function removes the authentication data and redirects the user to the login page. To prevent an infinite loop in case the refresh request itself returns 401, check if the failed request is the refresh request and log out accordingly.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Monday 10 August →