首页 > 解决方案 > Nestjs拦截器如何捕获http 401错误并重新提交原始请求

问题描述

我需要编写一个http头拦截器来添加授权头,如果出现401错误,请提交另一个新令牌的请求,然后用新令牌重新提交原始请求。

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);

      }),
                
    );
  }

但是 next.handle(originalRequest) 不起作用。如何在拦截器中重新提交原始请求?非常感谢您的帮助。

标签: nestjs

解决方案


我刚刚遇到了一个类似的问题,我可以从异常过滤器中捕获异常,但在拦截层中不能这样做。

于是我查了一下说明书,发现上面写着:

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).

因此,如果异常是从 AuthGuard 上下文中抛出的(包括 AuthService 中的 validate 方法),最好通过像这样扩展 Authguard 来移动附加逻辑:

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

或者只是使用自定义的异常过滤器。


推荐阅读