Angular 4 and OAuth - Intercept 401 responses, refresh the access token and retry request

隐身守侯 提交于 2019-11-28 02:22:43

Your function intercept must return always a Observable < HttpEvent < any > >. Your code is a bit "bizarro". The main problem I see is that you use "do" to catch the error. "do" not modify the request.

I have a intercept in this way (I hope the code can help you)

constructor(private inj: Injector) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //if the request has "Authorization" we return the request
    if (req.headers.has('Authorization'))
      return next.handle(req);

    //I get here the AuthService
    const auth = this.inj.get(AuthService);

    //create the httpHeaders
    const httpHeaders = new HttpHeaders()
      .set('Content-Type', 'application/json; charset=utf-8')
      .set('Authorization', '' + auth.SID) //<-- I use auth.SID

    const authReq = req.clone({ headers: httpHeaders });

    return next.handle(authReq).catch((err: any) => { //<--if error use a catch
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          //auth.recoverSID return a Observable<{value:new SID}>
          //use switchMap to really return next.handle(authReq)
          return auth.recoverSID().switchMap((value: IResponse) => {
            let httpHeaders = new HttpHeaders()
              .set('Content-Type', 'application/json; charset=utf-8')
              .set('Authorization', '' + value.SID)

            const authReq = req.clone({ headers: httpHeaders });
            return next.handle(authReq);
          })
        };
      }
      //Other case throw an error
      return Observable.throw(err);
    });
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!