Angular Authguard displays a blank page

771 views Asked by At

I'm using AuthGuard for some of my routes:

  {
    path: "dashboard",
    component: DashboardComponent,
    pathMatch: "full",
    canActivate: [RoleGuardService],
    data: {
      expectedRole: Role.ROLE_ADMIN,
    },
  },

And my roleguard.service

@Injectable()
export class RoleGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean {
    const expectedRole = route.data.expectedRole;
    if (!this.auth.hasRole(expectedRole)) {
      this.router.navigate(["login"], {
        queryParams: { returnUrl: state.url },
      });
      return false;
    }
    return true;
  }
}

If I log into the application and then use the UI to navigate to the dashboard everything works as expected. If I enter the URL in the browser localhost:4200/dashboard I get a blank page.

What am I missing?

Edit: typo

Edit: this is my current authService:

  public hasRole(r: string): boolean {
    let hasRole = false;
    this.getCurrentRoles().forEach((role) => {
      if (role.authority === r) {
        hasRole = true;
      }
    });
    return hasRole;
  }
1

There are 1 answers

2
Rajat On

In case of directly hitting the URL your expectedRole will be always false and since you have not provided any router.navigate for false condition therefore you get the blank page.

You can subscribe to the service which gives the correct value of expectedRole and than define your if statement conditions accordingly. This would work in all cases.

For Example:

Service:

  private isAdmin = new BehaviorSubject<boolean>(this.checkForAdmin());
  isUserAdmin = this.isAdmin.asObservable();

  checkForAdmin():boolean
  {
    const userName = localStorage.getItem("userName");

    if(userName == "Admin") //Replace with your expectedRole check
    {
      return true
    }
    return false;

  }

Inside Guard:

this.adminService.iAdmin.subscribe(result=>this.userAdmin=result)
        if (this.userAdmin) {
    
          return true;
        }
        else
        {
          console.log('Could not authenticate Admin');
       
       // to the desired or default page

          this.router.navigate(['dashboard'],{queryParams:{'redirectURL':state.url}});
          //return false;
        }