guirms
guirms

Reputation: 405

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?

Upvotes: 1

Views: 818

Answers (2)

kasmi zoubeir
kasmi zoubeir

Reputation: 46

I recommend this as augh.guard

class PermissionsService {
status:any
  constructor(private router: Router, private _auth:LoginService) {
      
    
  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    
   return this._auth.authMe().pipe(

    catchError((err:any)=>{
      this.router.navigate(['/admin/login'])
          return   throwError(()=> new Error("some error"))
           
          }
   ))
    
  }
}

export const authGuard: CanActivateFn = (next: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean>  => {
  return inject(PermissionsService).canActivate(next, state);
}

and the service auth is

//basecly what this method did is send a get method to the server if the token is good and not expired and not thouch is mean is the one who thje server generate from the login it will send us the user and if not will send a forbiden Error

 authMe():Observable<any>{
    return this.http.get<any>(`${this.serverUrl}/auth/meAdmin`)
    
   }

Upvotes: 0

SELA
SELA

Reputation: 6878

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.

Upvotes: 2

Related Questions