Angular 4.3 - HTTP Interceptor - refresh JWT token

前端 未结 4 612
清酒与你
清酒与你 2020-12-29 14:50

I need to react (in interceptor class) on 403 Forbidden HTTP status (to obtain/refresh) JWT token and retry the request with fresh token.

In the code below, when ser

4条回答
  •  一整个雨季
    2020-12-29 15:23

    My final solution to this problem:

    @Injectable()
    export class WebApiInterceptor implements HttpInterceptor {
      constructor(private tokenService: TokenService) {
      }
    
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
        console.log('*An intercepted httpRequest*', req, this.tokenService.accessToken);
        const authReq = this.authenticateRequest(req);
        console.log('*Updated httpRequest*', authReq);
        return next.handle(authReq)
          .map((event: HttpEvent) => {
            if (event instanceof HttpResponse) {
              console.log('*An intercepted httpResponse*', event);
              return event;
            }
          })
          .catch((error: any) => {
            if (error instanceof HttpErrorResponse) {
              if (error.status === 403 && error.url !== environment.authEndpoint) {
                return this.tokenService
                  .obtainAccessToken()
                  .flatMap((token) => {
                    const authReqRepeat = this.authenticateRequest(req);
                    console.log('*Repeating httpRequest*', authReqRepeat);
                    return next.handle(authReqRepeat);
                  });
              }
            } else {
              return Observable.throw(error);
            }
          })
      }
    }
    

    Function

    authenticateRequest(req)
    

    just adds Authorization header to the copy of original request

    Function

    obtainAccessToken()
    

    get fresh token form authorization server and stores it

提交回复
热议问题