user16592152
user16592152

Reputation: 13

Angular - AuthGuard & Auth Service - Observable always return TRUE

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.

UPDATE:

Network console response

Upvotes: 1

Views: 50

Answers (1)

Sergey Barabanov
Sergey Barabanov

Reputation: 86

In the list of routes in the image, you do not use AuthorisedUserGuard, but AuthGuard (it is not clear what it is). Use AuthorisedUserGuard.

I also want to add:

You don't need to use Promise, you already have an Observable. Guard can use Observable (MaybeAsync) in the output.

Remove async/await, and return a simple Observable. If you need to forward if false, then use tap().

For info: https://angular.dev/api/router/CanActivate https://angular.dev/api/router/MaybeAsync

Upvotes: 0

Related Questions