Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs Interceptor how to catch http 401 error and resubmit original request

Tags:

nestjs

I need to write an http header interceptor to add Authorization header, if there is a 401 error, submit another request for a new token, then resubmit the original request with the new token.

intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    const request = context.switchToHttp().getRequest();
    const response = context.switchToHttp().getResponse();

    return next.handle().pipe(

      catchError(async error => {

        if (error.response.status === 401) {

          const originalRequest = error.config;

          var authRes = await this.authenticationService.getAccessToken();
          
          this.authenticationService.accessTokenSubject.next(authRes.access_token);

          // I need to resubmit the original request with the new token from here
          // but return next.handle(originalRequest) doesn't work

        }
        return throwError(error);

      }),
                
    );
  }

But next.handle(originalRequest) doesn't work. How to resubmit the original request in the interceptor? Thank you very much in advance for your help.

like image 477
travelinglion Avatar asked Oct 16 '25 02:10

travelinglion


1 Answers

I just encountered a similar problem, where I can catch the exception from exception filter but can't do so in interception layer.

So I looked up the manual and found it says:

Any exception thrown by a guard will be handled by the exceptions layer 
(global exceptions filter and any exceptions filters that are applied to the current context).

So, if the exception is thrown from AuthGuard context(including the validate method in your AuthService), probably better to move the additional logic by extending the Authguard like this:

export class CustomizedAuthGuard extends AuthGuard('strategy') {
    handleRequest(err, user, info, context, status) {
        if (err || !user) {
            // your logic here
            throw err || new UnauthorizedException();
        }
        return user;
    }
}

or simply using customized exception filter.

like image 123
Null Bite Avatar answered Oct 18 '25 02:10

Null Bite