Angular2-jwt: Refresh token automatically before sending any request

Created on 10 Apr 2018  ·  6Comments  ·  Source: auth0/angular2-jwt

i'm using v1.1.0

i need to refresh the token if it's expired before sending any request once or automatically

i don't want to do it manually each time i send a request like this for example:

getSomeData(){
    if(this.helper.isTokenExpired())
    {
        this.authService.refreshToken().subscribe(result => {
          //request the requird dat with the new access token
        })
    }
    else
    {
        //request the requird data
    }
  }

Am I doing it wrong? Is there another way to achieve that?

stale

Most helpful comment

@crooksey How does this work, your refreshToken() is a callback. it doesent look like you are waiting for the token before adding it to the headers.

In any case, i am waiting for the token before adding it to my headers. But for some reason , my api call still fires before the interceptor is able to refresh the token and append it to the headers. That results in an error for me because the token is expired before the interceptors is able to refresh the token.

All 6 comments

Yes, write your own Http interceptor to send the JWT with all your requests, then add the logic/code in here to refresh the token (if necessary) before submitting the request.

Example:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class JwtHttpInterceptor implements HttpInterceptor {
  constructor() {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('rawJWT');
      let clone: HttpRequest<any>;
      if (token) {
        if (token.expired) {
            // renew token
            this.authService.refreshToken().subscribe(result => {
            token = result.token
        })
        }
        clone = request.clone({
          setHeaders: {
            Accept: `application/json`,
            'Content-Type': `application/json`,
            Authorization: `Bearer ${token}`
          }
        });
      } else {
        clone = request.clone({
          setHeaders: {
            Accept: `application/json`,
            'Content-Type': `application/json`
          }
        });
      }
      return next.handle(clone);
  }
}

Then in app.module.ts (note you have to import the above first as normal)

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtHttpInterceptor, multi: true },

@crooksey How does this work, your refreshToken() is a callback. it doesent look like you are waiting for the token before adding it to the headers.

In any case, i am waiting for the token before adding it to my headers. But for some reason , my api call still fires before the interceptor is able to refresh the token and append it to the headers. That results in an error for me because the token is expired before the interceptors is able to refresh the token.

See this gist if you need to support the refresh token pattern.

It implements an additional RefreshTokenInterceptor that automates the renewall of JWT in the HttpClient data stream.

Currently it's not configurable, and you have to adjust the code to your own need. (Tested on angular 6.)

+1

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If you have not received a response for our team (apologies for the delay) and this is still a blocker, please reply with additional information or just a ping. Thank you for your contribution! 🙇‍♂️

before adding it to the headers.

In any case, i am waiting for the token befor

Could you share your the code please.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JaxonWright picture JaxonWright  ·  4Comments

getglad picture getglad  ·  5Comments

hang321 picture hang321  ·  4Comments

UlyssesAlves picture UlyssesAlves  ·  5Comments

mahendra2125 picture mahendra2125  ·  4Comments