Angular - AuthGuard & Auth Service - Observable always return TRUE

Discussão em 'Angular' iniciado por user16592152, Fevereiro 28, 2025.

  1. user16592152

    user16592152 Guest

    I am trying to protect my routes my using AuthGuards. The authGuard will call the AuthService to which will access and API to check the user belongs to a certain AD group.

    The isAuthorised() method under the authService always returns true even when I set it to false. AuthGuard class:

    import { Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate } from '@angular/router';
    import { Injectable, inject } from '@angular/core';
    import { AuthService } from '../shared/auth.service';



    export class AuthorisedUserGuard implements CanActivate {

    constructor(private authService: AuthService, private router: Router, private route: ActivatedRouteSnapshot) { }

    async canActivate() {

    let result = await this.authService.isAuthorisedUser(this.route.data['role']).toPromise();
    if (!result) {
    this.router.navigate(['/unauthorised'])
    }
    return true;
    }
    }


    AuthService:

    export class AuthService {

    constructor(private router: Router, private http: HttpClient) {
    }

    URL_Config: Configuration = new Configuration();
    public accessGranted: boolean = false;
    public route: string = "";

    isAuthorisedUser(role: string): Observable<boolean> {
    this.route = role;
    let apiURL = `${this.URL_Config.URL}/api/UserAccess/checkUserAccess?route=${this.route}`;
    return this.http.get<boolean>(apiURL, { withCredentials: true });

    }
    }


    I have tried to remove the obseravle method to return the boolean value but in order for AuthService to work you need it to be observable.

    Continue reading...

Compartilhe esta Página