Updating token (JWT) using interceptor in Angular 6

At first, I had a function that checked for the existence of a token and if it wasn't present, redirected the user to the login page. Now, I need to incorporate the logic of token refreshing when it expires using a refresh token. However, I'm encountering a 401 error. The refresh function is not completing in time, causing the interceptor to proceed to the error state. How can I modify the code to ensure that it waits for the refresh to complete, fetch a new token, and avoid redirecting to the login page?

TokenInterceptor

import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Injectable, Injector} from "@angular/core";
import {AuthService} from "../services/auth.service";
import {Observable, throwError} from "rxjs";
import {catchError, tap} from "rxjs/operators";
import {Router} from "@angular/router";
import {JwtHelperService} from "@auth0/angular-jwt";

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptor implements HttpInterceptor{

  private auth: AuthService;

  constructor(private injector: Injector, private router: Router) {}

  jwtHelper: JwtHelperService = new JwtHelperService();

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

    this.auth = this.injector.get(AuthService);

    const accToken = this.auth.getToken();
    const refToken = this.auth.getRefreshToken();

    if ( accToken && refToken ) {

      if ( this.jwtHelper.isTokenExpired(accToken) ) {
        this.auth.refreshTokens().pipe(
          tap(
            () => {
              req = req.clone({
                setHeaders: {
                  Authorization: `Bearer ${accToken}`
                }
              });
            }
          )
        )
      } else {
        req = req.clone({
          setHeaders: {
            Authorization: `Bearer ${accToken}`
          }
        });
      }

    }
    return next.handle(req).pipe(
      catchError(
        (error: HttpErrorResponse) => this.handleAuthError(error)
      )
    );
  }

  private handleAuthError(error: HttpErrorResponse): Observable<any>{
    if (error.status === 401) {
      this.router.navigate(['/login'], {
        queryParams: {
          sessionFailed: true
        }
      });
    }
    return throwError(error);
  }

}

AuthService

import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable, of} from "rxjs";
import {RefreshTokens, Tokens, User} from "../interfaces";
import {map, tap} from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class AuthService{

  private authToken = null;
  private refreshToken = null;

  constructor(private http: HttpClient) {}

  setToken(authToken: string) {
    this.authToken = authToken;
  }

  setRefreshToken(refreshToken: string) {
    this.refreshToken = refreshToken;
  }

  getToken(): string {
    this.authToken = localStorage.getItem('auth-token');
    return this.authToken;
  };

  getRefreshToken(): string {
    this.refreshToken = localStorage.getItem('refresh-token');
    return this.refreshToken;
  };

  isAuthenticated(): boolean {
    return !!this.authToken;
  }

  isRefreshToken(): boolean {
    return !!this.refreshToken;
  }

  refreshTokens(): Observable<any> {

    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + this.getRefreshToken()
      })
    };

    return this.http.post<RefreshTokens>('/api2/auth/refresh', {}, httpOptions)
      .pipe(
        tap((tokens: RefreshTokens) => {
          localStorage.setItem('auth-token', tokens.access_token);
          localStorage.setItem('refresh-token', tokens.refresh_token);
          this.setToken(tokens.access_token);
          this.setRefreshToken(tokens.refresh_token);
          console.log('Refresh token ok');
        })
      );
  }

}

Answer №1

To achieve this, you need to follow these steps:

const firstRequest = customizeRequest(req);

return next.handle(firstRequest).pipe(
   catchError(
      error => {
         if (error instanceof HttpErrorResponse) {
            if (error.status === 401 || error.status === 403) {
               if (firstRequest.url === '/api2/auth/refresh') {
                  authentication.setToken('');
                  authentication.setRefreshToken('');
                  this.router.navigate(['/login']);
               } else {
                  return this.auth.refreshTokens()
                    .pipe(mergeMap(() => next.handle(customizeRequest(req))));
               }
            }
            return throwError(error.message || 'Encountered a server error');
         }
      }
    )
 );

The customizeRequest function should be implemented as shown below:

private customizeRequest(request: HttpRequest<any>): HttpRequest<any> {
    return request.clone({
       setHeaders: {
           Authorization: `YourToken`
       }
    });
}

Answer №2

It seems you forgot to subscribe to the refreshTokens().pipe() code in your example. Remember, without a subscription, the observable will not be executed.

Answer №3

req = this.auth.generateNewToken().pipe(
      switchMap(() => req.clone({
            setHeaders: {
              Authorization: `Bearer ${this.auth.getToken()}`
            }
          }))
      )

Initially, this code snippet initiates the generateNewToken function to refresh the access token, followed by fetching the updated token using this.auth.getToken(). It's important to note that although the new token is obtained, the previous token value stored in accToken remains unchanged until the code gets executed again.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to access NgForm.value in ngAfterViewInit phase

In my template driven form, I need to save the initial values of controls. Initially, I thought that using the ngAfterViewInit method would be ideal since it is called after the template is rendered, allowing me to access and store the value of form contro ...

When attempting to retrieve data from an API in Angular 8, I encountered difficulties in dynamically creating a formArray within a formArray

I am struggling to dynamically create form controls based on the data received, specifically for fields like task and template name. Your assistance is greatly appreciated. { "items": [ { "templatename": "Defult" ...

Changing the time in Angular while converting a string to a date object has proven to be

Can anyone help me with a problem I'm having trying to convert a String into a Date object without it being affected by timezone changes? Specifically, when I receive 2020-07-14T15:27:39Z from an http get request, I need to convert this into a Date o ...

React date format error: RangeError - Time value is invalid

I'm utilizing a date in my React app using the following code: const messageDate = new Date(Date.parse(createdDate)) const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const ...

Sending geographic coordinates from a child component in a React application using Google Maps to its parent component within a functional

My current project involves creating a map component in my React application using @googlemaps/react-wrapper. I followed the example from Google Maps and successfully added an event to refresh coordinates when dragging the marker. Now, I need to call the m ...

When using Vimeo's JS API, the player.loadVideo() method will revert the player's settings back to their default options

Using Vimeo's player.js API, I'm setting options on the player to disable the title upon initialization: var options = { id: 59777392, title: false }; var vimPlayer = new Vimeo.Player('myDiv', options); The video player correc ...

In JavaScript, the code is designed to recognize and return one specific file type for a group of files that have similar formats (such as 'mp4' or 'm4v' being recognized as 'MOV')

I am working on a populateTable function where I want to merge different file types read from a JSON file into one display type. Specifically, I am trying to combine mp4 and m4v files into MOV format. However, despite not encountering any errors in my code ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

Why does variable passing use 'object Text' instead of passing values?

In my for loop, I am dynamically creating a table with radio buttons and trying to create labels dynamically as well. However, when I pass the variable to the label text node, it prints out 'object Text' on the page instead of the expected value. ...

In JavaScript, Identify the filename selected to be attached to the form and provide an alert message if the user chooses the incorrect file

I have a form in HTML that includes an input field for file upload. I am looking to ensure that the selected file matches the desired file name (mcust.csv). If a different file is chosen, I want to trigger a JS error. Below is the form: <form name="up ...

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

What is the best way to incorporate this in a callback function?

Utilizing a third-party component requires creating an object for configuration, such as itemMovementOptions in the given code sample. export class AppComponent implements OnInit { readonly itemMovementOptions = { threshold: { horizontal: ...

html - automatically populating input fields when the page loads

Currently, I have an HTML form embedded in the view and I am looking for a way to automatically populate specific input fields with json variables obtained from the server. Instead of manually writing JavaScript code for each field, my goal is to access th ...

Is there a way to sort through an array based on a nested value?

Within an array of objects, I have a structure like this: "times": [{ "id" : "id", "name" : "place", "location" : "place", "hours" : [ {"day": " ...

JavaScript: Transforming a key-value pair collection into an array of objects

I'm looking to convert a dictionary into a list of dictionaries using JavaScript. Can someone help me with that? var dict = { "apple" : 10, "banana" : 20, "orange" : 30 } var data = [ {"apple" : 10}, {"ban ...

The Jquery .clone() function presents issues in Internet Explorer and Chrome browsers, failing to perform as expected

I need to duplicate an HTML control and then add it to another control. Here is the code I have written: ko.bindingHandlers.multiFileUpload = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { va ...

Test for comparing objects partially using Jasmine Array

Is there a specific method in jasmine for checking if an array partially matches another array by comparing objects? Considering that the arrays could potentially contain large amounts of data from test files, is there a way to avoid comparing each indivi ...

Developing a constrained variable limited to specific values

Recently delving into Typescript - I am interested in creating a variable type that is restricted to specific values. For instance, I have an element where I want to adjust the width based on a "zoom" variable. I would like to define a variable type call ...

A guide to transferring modules between component files in JavaScript

My query pertains to the handling of imports in web pages. When a file is imported into another, do the declarations and imports from the imported file become available in the file where it is being imported? A suggestion was made for me to import a compo ...

What is the best method for expanding the width of a <rect> element with animateTransform?

How can I make a <rect> in SVG expand its width using animateTransform based on a specified value? Additionally, I want the color of the <rect> to change according to the following conditions: If the <rect> value is between 0 and 29: {f ...