how to prevent user from routing , when token is expired

Issue

I am working on Angular 7 Application

  • I am using JSON Web Tokens (JWT) to secure my Angular Application
  • I want to check weather token is expired , and if it is expired I want to prevent user from routing . except home page and next to home page
  • I just want the token won’t be useful if it is expired, so that the user should be considered “not
    authenticated”.
  • I tried the same using npm install –save @auth0/angular-jwt@beta ,
    but I don’t want to do the same using any dependency
  • I want to do it using routing guards , I tried it with CanActivate
    but it is not working

Solution

If you use CanActivate then you probably have to make a network call on every route change to probe if the authentication has expired. At least that is what I can possibly think.

You can instead check this in backend if possible and reject all calls, API calls and all other calls using 401 Unauthorized access status code.

With this, you can setup an interceptor to handle 401 and redirect user to login page or add a logic to refresh token as you like. You can also pass Location header along and use it for redirect.

import {throwError as observableThrowError,  Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private router: Router) {}
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            catchError((err: any, caught) => {
                if (err instanceof HttpErrorResponse) {
                    if (err.status === 401) {
                       // Redirect or refresh token.
                    }
                    return observableThrowError(err);
                }
            }));
    }
}

I do hope there will be other solutions out there.

Answered By – sabithpocker

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.