angularauthenticationauthorizationhttponlycookie-httponly

How can I authenticate user token in Angular Guard if I am using Http-Only?


I know that the safe approach to work with auth tokens is to use Http-Only, because with that, the JWT token will be read and set only on the server side. Ok, that makes sense to me.

My problem is: How can I apply logic to allow users access to some routes only when they are logged in successfully? Currently, I'm storing the auth token in session storage and using Angular auth guards to validate if the auth token is valid. But how would I validate the auth token in the Angular auth guards if the auth token is not readable on the client side?


Solution

  • You need to implement a route guard. It does have CanActivate which you can leverage and use accordingly.

    Refer the below example of how to use Angular Auth Guard with CanActivate:

    // auth.guard.ts
    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
    import { AuthService } from './auth.service';
    import { Observable } from 'rxjs';
    
    @Injectable({
      providedIn: 'root',
    })
    export class AuthGuard implements CanActivate {
      constructor(private authService: AuthService, private router: Router) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.authService.isAuthenticated().pipe(map((isAuthenticated) => {
          if (isAuthenticated) {
            return true;
          } else {
            // Redirect to login page if not authenticated
            this.router.navigate(['/login']);
            return false;
          }
        }));
      }
    }
    

    From your auth service you can get authorization for each route and decide if the user can be navigated to the route the user planning to go to. if not provide route user to another no privilege path.

    Not that the CanActivate route guard triggers each time the user tries to access a different route.