Updating the JWT token in Angular 6 and making a new request with the updated token

When my JWT authentication token expires (verified by the backend), I need to call a refresh token API and resend the last failed request due to the expired token.
I have an Interceptor in place, but I must update the authentication header before sending the request and wait for the refreshToken call.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const { shouldRetry } = this;
    return next.handle(request).pipe(  
      retryWhen(genericRetryStrategy({
        shouldRetry
      })),

      catchError(err => {
        // If status is 401, token is invalid so refresh it
        if (err.status === 401) {
          this.auth.refreshToken().subscribe(
            (apiResult: SessionTokenResponse) => {
              this.auth.saveToken(apiResult.token);
            },
            error => this.auth.logout()
          );
          request = request.clone({headers: request.headers.set('Authorization', 'Bearer ' + this.auth.getSessionToken)});
          return next.handle(request);
        }
        const error = err.error.message || err.statusText;
        return throwError(error);
      }),
    )
  }

Is this the correct approach to resend the call? How can I ensure the completion of refreshToken? Thank you

EDIT: I have updated the code with a revised version that appears to be functioning correctly. Currently testing it out.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { shouldRetry } = this;
return next.handle(request).pipe(
  retryWhen(genericRetryStrategy({
    shouldRetry
  })),

  catchError(err => {
    // If status is 401, token is invalid so refresh it
    if (err.status === 401) {
      this.auth.refreshToken().subscribe(
        (apiResult: SessionTokenResponse) => {
          this.auth.saveToken(apiResult.token);
          request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + apiResult.token) });
          next.handle(request).subscribe();
        },
        err => this.auth.logout()
      );          
    }else{
      const error = err.error.message || err.statusText;
      return throwError(error);
    }
  }),
)

}

Answer â„–1

If you understand the question correctly, you can use async to wait for the refresh token. You can verify the access for the current token or refresh it if it's invalid in the CanActivate function. Interestingly, on each request, the system will automatically check the access for the token so there is no need to add extra code in the interceptor.

In the authentication service:

     async isAuthenticated(){
     const response = await this.auth.refreshToken().toPromise();
     return response;
  }

In the CanActivate function:

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.authenticated= await this.Service.isAuthenticated();
    if(this.authenticated) {
         this.auth.saveToken(apiResult.token);
         return true;
      }
    else
        this.auth.logout();
        // navigate to login

}

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

(IONIC) Issue with MomentJS locale functionality not functioning properly post-building process

I am currently utilizing the IONIC Framework and incorporating Moment.js for handling dates. I have set all strings to be in French using the code below: moment.locale('fr'); Interestingly, this works perfectly on the "serve" mode of Ionic. Ho ...

Angular filtering is not functioning as expected

I have the following code in my template: <li class="row timeline-item" data-ng-repeat="item in data | filter:workoutFilter" data-ng-include="getTemplateUrl(item)"></li> And this is what I have in my controller: $scope.workoutFilter = nu ...

Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter. <div class="container" :style=&qu ...

Dynamic cell editing feature in PrimeNG table

Looking to implement the PrimeNG Table. https://i.stack.imgur.com/bQycr.png Check out the live demo on StackBlitz. The table has three editable columns. The "Property Name" column always displays a text box in edit mode, while the "Property Value Type" ...

Tips for setting `Cache: false` with the $.getJSON() function

I'm experiencing a caching problem with ajax calls in IE 10. The solution I found is to include cache: false in the ajax call, but I'm still having issues. How can I properly include Cache: false in my code? $.getJSON(url , function(data){ //som ...

Creating a function in JavaScript to return an Unsubscribe and Array from a Firebase Snapshot Listener in Svelte

In my SvelteKit project, I have integrated Firebase Firestore. I maintain a db.js file that contains various functions utilized in Svelte components. One such function is detailed below. export const Items = { async getMany() { let dbRef = db.c ...

Choosing the image that represents your website in Safari web previews

Every time I check iCloud.com on my Safari top sites, the thumbnail is always the same. I'm curious about how I can automate this for my own website. ...

Function fails to execute after drop-down menu selection

I set up a double drop-down feature and implemented my function calling code. However, after choosing an option from the drop-down menus, the function is not getting executed. The purpose of the code is to trigger a specific function based on the selectio ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

When users visit my contact HTML page, they are redirected to the contact PHP page, but unfortunately, the email is

I am currently facing an issue with my contact form. After filling out the form and hitting the "send" button, it redirects to the contact.php page but fails to send an email or work as intended. Can someone please assist me and identify what's causin ...

The correct method to effectively type out a JSON object

Recently, I came across an article on that mentioned the possibility of importing JSON objects into a TypeScript project. Intrigued, I decided to give it a try by importing the following JSON: { "defaultLanguage": "en", "languageMap": { "en": "En ...

Stop observing IntersectionObserver within the React.useEffect function

I'm attempting to retrieve the top and bottom measurements from multiple elements using the IntersectionObserver. However, once I have the measurements, I'm unsure how to stop observing the elements. The issue is that each element has a position ...

Having trouble with the installation of [email protected] on Windows 10 x64?

I am currently in the process of setting up hiredis on my Windows 64-bit operating system as it is a requirement for the node-celery package. My system specifications are as follows: Node v7.9.0 npm v4.5.0 Visual Studio Community 2013 with Update 5 (en_ ...

Changing URL parameters without refreshing the page using query strings

Is there a method similar to how Google adds and removes parameters from the URL in Gmail without requiring a postback? For example, when you start composing a draft, a "?compose=new" parameter is added to the URL. I was considering using `history.pushSta ...

Tips for updating information within a vue-component

I am working on a Vue component where I retrieve data from localStorage. Here is how I handle it: if (localStorage.getItem("user") !== null) { const obj_user = localStorage.getItem('user'); var user = JSON.parse(obj_user); } else { ...

When the tooltip component is triggered in a React application, the cursor is automatically directed to

I have been working on creating an input field that allows users to enter time as input. Here's the code snippet I am using: <InputMask mask="99:99" onBlur={handleOnBlur} onChange={(e) => { const ...

We encountered a surprising character "EOF" in the code. Could it be due to an unescaped "{" in the template? Please use "{{ '{' }}" to properly escape it

I encountered an issue while upgrading my angular 2 app from beta 9 to RC5. The error I received is in my form template. Below is the detailed error: zone.js:461 Unhandled Promise rejection: Template parse errors: Unexpected character "EOF" (D ...

Displaying array elements on a webpage using JavaScript in HTML

Looking to display multiple blocks in HTML using a JavaScript array. The array contains names such as: var name=['amit','mayank','jatin'];. I need to repeat a certain portion of code in order to show the elements of the array, ...

Is it possible in Vue.js to create a reactive functionality for a button using a watcher for "v-if" condition?

I have a userlist page with various profiles, including my own. A button is supposed to appear only when viewing my own profile. The issue arises when switching from a different profile to my own (changing the router parameter) - the button should show up ...