Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak and Angular - Cannot read property 'resourceAccess' of undefined

Tags:

angular

I have angular app and I try to add keycloak. I set up keycloak, but when I try to run angular app I get ERROR Error: Uncaught (in promise): An error happened during access validation. Details:TypeError: Cannot read property 'resourceAccess' of undefined

Angular version: 8.2.5 Keycloak-angular: 7.0.1 Keycloak-js: 7.0.0

Here is my auth.guard.ts

import { Injectable } from "@angular/core";
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { KeycloakService, KeycloakAuthGuard } from "keycloak-angular";

@Injectable()
export class AppAuthGuard extends KeycloakAuthGuard {
  constructor(protected router: Router, protected keycloakAngular: KeycloakService) {
    super(router, keycloakAngular);
  }

  isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    return new Promise(async (resolve, reject) => {
      if (!this.authenticated) {
        this.keycloakAngular.login();
        return;
      }

      const requiredRoles = route.data.roles;
      if (!requiredRoles || requiredRoles.length === 0) {
        return resolve(true);
      } else {
        if (!this.roles || this.roles.length === 0) {
          resolve(false);
        }
        let granted: boolean = false;
        for (const requiredRole of requiredRoles) {
          if (this.roles.indexOf(requiredRole) > -1) {
            granted = true;
            break;
          }
        }
        resolve(granted);
      }
    });
  }
}

here is my environment.ts

import { KeycloakConfig } from "keycloak-angular";

let keycloakConfig: KeycloakConfig = {
  realm: "realm5",
  url: "https://aaaaaa.net/auth",
  clientId: "admin"
};
export const environment = {
  production: false,
  keycloak: keycloakConfig
};

in app-routing.module.ts i import AppAuthGuard

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { AppAuthGuard } from "./auth/auth.guard";
import { HomeComponent } from "./home/home.component";
import { UsersComponent } from "./users/users.component";

const routes: Routes = [
{ path: "admin-app/home", component: HomeComponent, canActivate: 
[AppAuthGuard] },
{ path: "admin-app/users", component: UsersComponent, canActivate: 
[AppAuthGuard] },
{ path: "admin-app", redirectTo: "admin-app/home", canActivate: 
[AppAuthGuard] }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [AppAuthGuard]
})
export class AppRoutingModule {}

and in app.module.ts

    import { KeycloakAngularModule, KeycloakService } from "keycloak-angular";
    const keycloakService = new KeycloakService();
    @NgModule({
      declarations: [AppComponent, HomeComponent, UsersComponent, NavComponent],
      imports: [BrowserModule, AppRoutingModule, KeycloakAngularModule],
      providers: [{
         provide: KeycloakService,
         useValue: keycloakService
      }],
     bootstrap: [AppComponent]
    })
   export class AppModule {ngDoBootstrap(app) {
     keycloakService
  .init()
  .then(() => {
    console.log("[ngDoBootstrap] bootstrap app");

    app.bootstrap(AppComponent);
  })
  .catch(error => console.error("[ngDoBootstrap] init Keycloak failed", error));

}}

like image 694
Arter Avatar asked Sep 23 '19 07:09

Arter


2 Answers

You are manually Bootstrapping the Angular App, so you have to:

  • remove the bootstrap: [Array] from the NgModule definition.

  • add entryComponents: [AppComponent] to the NgModule definition. Then the keycloak Init method will actually execute before needed in the AuthGuard.

   @NgModule({
     declarations: [AppComponent, HomeComponent, UsersComponent, NavComponent],
     imports: [BrowserModule, AppRoutingModule, KeycloakAngularModule],
     providers: [{
        provide: KeycloakService,
        useValue: keycloakService
     }],
    entryComponents: [AppComponent]
   })
like image 188
Fidel Gonzo Avatar answered Nov 04 '22 03:11

Fidel Gonzo


There is actually a bug in keycloak-js 7.0.0.

When you use keycloak-js 7.0.1 instead (which is available now), it works. I'm not sure btw. if you also need the changes Fidel Gonzo provided but i had the same issue as you.

https://github.com/mauriciovigolo/keycloak-angular/issues/153

like image 1
sigi Avatar answered Nov 04 '22 05:11

sigi