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

前端 未结 1 1710
无人共我
无人共我 2020-12-07 04:59

As the title says, I am working on an Angular 4 project with OAuth authentication.

Whenever an http request responds with status code 401 I am intercepting the reque

相关标签:
1条回答
  • 2020-12-07 05:35

    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);
        });
      }
    
    0 讨论(0)
提交回复
热议问题