Search code examples
angularauthenticationaccess-tokenwebapi

WebApi and Angular 2+ - Authentication - Token expired - Return to login


I have a angular client application protected by a login. When I log in, the web API returns me the access token that expire in x minutes. When the access token is expired I want return to the login but I do not understand how to do it.

This is my ErrorInterceptor class:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(catchError(err => {
        if (err.status === 401) {
            // auto logout if 401 response returned from api
            this.authenticationService.logout();                
            location.reload(true);
        }
        
        const error = err.error.message || err.statusText;
        return throwError(error);
    }))
  }
}

But when token is expired nothing happens.

Someone can give me some advice?


Solution

  • Use HttpInterceptor:

    https://angular.io/api/common/http/HttpInterceptor

    In Angular create an Interceptor that will check for errStatus 401 (Unauthorized).

    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor {
        constructor(private logoutService: LogoutService) { /* empty */ }
    
        public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            return next.handle(req).catch((err: HttpErrorResponse) => {
                if (err && err.status) {
    
                    this.handleRequestErrors(err.status);
                }
    
                return Observable.throw(err);
            });
        }
    
        /**
         * handleRequestErrors
         * @param err: The HTTP Error Code Status
         */
        private handleRequestErrors(errStatus: number) {
            switch (errStatus) {
                case 401: { // Unauthorized
                    this.logoutService.removeStoredAuthentication();
                    break;
                }
            }
        }
    }