-1

I am trying to implement refresh tokens in my angular app. I have written an http interceptor which tries to get a new access token whenever I get a 401 error. I don't know why but this doesn't work. I am still getting a 401 response.

Nebex Elias
  • 252
  • 1
  • 3
  • 14

2 Answers2

0

You need to check if response code is 401 then request for refresh token and wait for response after receiving response process pending requests. refresh token with http interceptor

Nirav Patel
  • 16
  • 1
  • 3
0

Generate refreshToken before request if need it

export class HttpRequestInterceptor implements HttpInterceptor {
constructor(private router: Router, private service: AuthService) { }

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

    return from(this.tokenHandler(request)).pipe(mergeMap((req: HttpRequest<any>) => {
        return next.handle(req).pipe(catchError(err => {
            if ([401].indexOf(err.status) != -1) {
                // auto logout if 401 response returned from api
            }                
            else {                    
                throw err;
            }

            return EMPTY;
        }));
    }));
}

private async tokenHandler(request: HttpRequest<any>): Promise<HttpRequest<any>> {
    if (request.url.indexOf("REFRESHTOKEN_URL") == -1) {
        await this.service.GenerateNewTokenIfNeed(); //Important this function would be async and put httpClient call to ToPromise() and await it. Save token somewhere and get from there to #token# place
    }
    else {
        //RefreshTokenRequest
    }

    const authReq = request.clone({
        setHeaders: {
            Authorization: "Bearer #token#"
        },
    });

    return authReq;
}
Péter
  • 273
  • 1
  • 10