1

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
Testing Anurag
  • 603
  • 4
  • 13
  • 26
  • If you want a complete solution for the problem you are having, I think you should split you question into -at least- 3 separate questions as it is too broad this way. 1st for public and authenticated routes. 2nd for how to check token validity and 3rd for route guards. – Harun Yilmaz Mar 12 '19 at 07:38
  • https://stackoverflow.com/questions/38915893/angular2-prevent-authenticated-users-from-accessing-specific-routes – Testing Anurag Mar 12 '19 at 07:58

1 Answers1

1

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.

sabithpocker
  • 15,274
  • 1
  • 42
  • 75