How to intercept 401 unauthorized and add the new Authorization code?

Viewed 2279

I want to detect a 401 response code for my HTTP request in one component:

@Injectable()
export class InterceptorProvider implements HttpInterceptor {

  constructor(private authService: AuthenticationService) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      console.log(request);
      return next.handle(request);
  }

How can I catch the error, do a refresh token request and let the other component continue if the response code is ok?

UPDATE

@Injectable()

export class InterceptorProvider implements HttpInterceptor {

constructor(private authService: AuthenticationService, private storage: Storage) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  console.log(request);
  return next.handle(request)
    .pipe(tap(event => {
        if (event instanceof HttpResponse) {
        }
      }, err => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 401) {

            console.log(err);
            console.log("Retriving user....");
           let user = new User();
this.storage.get('username').then((result)=>{
  console.log(result);
  user.username = result;
  let pass = this.storage.get('password').then((result)=>{
    console.log(result);
    user.password = result;
    console.log(user.username);
console.log(user.password);

  console.log("user ok");
  this.authService.login(user.username, user.password).toPromise().then(response=>{
    let token = response['message'];
    this.storage.set('token', token);
    this.addToken(request, token);
    return next.handle(this.addToken(request, token));
  });

  });
});
          }
        }
      })
    )
}

// Adds the token to your headers if it exists
private addToken(request: HttpRequest<any>, token: any) {
    if (token) {
        let clone: HttpRequest<any>;
        clone = request.clone({
            setHeaders: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                Authorization: token
            }
        });
        return clone;
    }

    return request;
}

}

This new version does the re-login operation, but it doesn't go further, it seems some problem with the re do of the original request, added with the new access token; where am I wrong?

UPDATE

This is the console error:

core.js:9110 ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":401,"statusText":"Unauthorized","url":"https://www.fantacalciopizza.it/php/formazioniinviatejson2.php","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://www.fantacalciopizza.it/php/formazioniinviatejson2.php: 401 Unauthorized","error":"\n\n"}
at resolvePromise (zone-evergreen.js:797)
at resolvePromise (zone-evergreen.js:754)
at zone-evergreen.js:858
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:34182)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
at drainMicroTaskQueue (zone-evergreen.js:559)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:469)
at invokeTask (zone-evergreen.js:1603)

Then there is the try to Login, I got the response, but the cloned request doesn't seem to be executed; where am I wrong?

3 Answers

Try like this:

 return next.handle(authRquest)
        .pipe(
          tap(event => {
            if (event instanceof HttpResponse) {
            }
          }, err => {
            if (err instanceof HttpErrorResponse) {
              if (err.status === 401) {
                // handle error
              }
            }
          })
        )

I usually do this on the interceptor:

return next.handle(req).pipe(
    tap<HttpResponse<any>>(
        res => {
            // Logic if response is ok
        },

        err => {
            // Logic if response is not ok

            if(err.status === 401) {
                // Handle the error
            }
        }
    )
)

After registering the UnauthorizedInterceptor in providers of Root module , it will automatically detect the 401,403 errors

In unauthorized.interceptor.ts

@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].indexOf(err.status) !== -1) {               
                // YOUR  MESSAGE
            }

            const error = err || err.statusText;
            return throwError(error);
        }))
    }
}

In AppModule.ts

@NgModule({
    ...,
   providers: [{
      provide: HTTP_INTERCEPTORS,
      useClass: UnauthorizedInterceptor,
      multi: true
    }]
})
Related