Angular2-jwt: intercept requested api route

282 Views Asked by At

I'm implementing a jwt refresh mechanism. I'm using auth0/angular2-jwt with Angular 7. When I'm accessing a protected route, I'm sending a request to /api/v1/protected with my access_token in the Authorization header. When I need to refresh the jwt token, I've got to send a request to /api/v1/auth/refresh with my refresh_token in the Authorization header. What I can't figure out is how to select which token I'll send based on the api route.

app.module.ts

import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
import { HttpClientModule } from '@angular/common/http';

import { TokenService } from './services/token.service';

export function jwtOptionsFactory(tokenService) {
  return {
    tokenGetter: () => {
      return tokenService.getAsyncToken();
    },
      whitelistedDomains: [
        'localhost',
        'localhost:80',
        'localhost:443',
        'localhost:4200', 
      ],
      blacklistedRoutes: [],
      throwNoTokenError: false,

  }
}
...
@NgModule({
...
  imports: [
    HttpClientModule,
    JwtModule.forRoot({
      jwtOptionsProvider: {
        provide: JWT_OPTIONS,
        useFactory: jwtOptionsFactory,
        deps: [TokenService]
      }
    }),

  ],
...
})

token.service.ts

import { Injectable } from '@angular/core';

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

  constructor() { }

  getAsyncToken(){
    // This is the part in question
    if (route=='/api/v1/auth/refresh') {
       return localStorage.getItem('refresh_token');
    } 
    return localStorage.getItem('access_token');

  }


}

My plan B is to blacklist the refresh route in angulat-jwt and write a custom interceptor. But I'd like to know if there's something I messed. Is this possible to intercept the api call (check the api route) in my token service?

0

There are 0 best solutions below