0 votes
in Angular by
How do you handle token revocation and refresh in Angular applications?

1 Answer

0 votes
by
In Angular applications, token revocation and refresh are typically handled using the following steps:

1. Implement an authentication service that handles user login, logout, and token management.

2. Use HttpInterceptor to intercept HTTP requests and attach access tokens to outgoing API calls.

3. Monitor responses for 401 Unauthorized errors, indicating expired or revoked tokens.

4. When a 401 error is detected, use a Refresh Token to request a new Access Token from the authentication server.

5. Update the stored tokens in the authentication service with the new Access Token.

6. Retry the original failed request with the updated Access Token.

Here’s a code example of an HttpInterceptor implementation:

@Injectable()

export class AuthInterceptor implements HttpInterceptor {

  constructor(private authService: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return this.authService.getAccessToken().pipe(

      take(1),

      switchMap(token => {

        const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });

        return next.handle(authReq).pipe(

          catchError(error => {

            if (error.status === 401) {

              return this.authService.refreshToken().pipe(

                switchMap(newToken => {

                  const retryReq = req.clone({ setHeaders: { Authorization: `Bearer ${newToken}` } });

                  return next.handle(retryReq);

                })

              );

            }

            return throwError(error);

          })

        );

      })

    );

  }

}

Related questions

+1 vote
asked Jan 23, 2022 in Angular by sharadyadav1986
0 votes
asked Feb 23 in Angular by rahuljain1
...