I'm trying to set up a keylock with angular. Everything works if in the keycloak admin panel I don't select settings "Access settings " --> "Root URL" and "Home URL" in my client's settings. If they are selected, then I get an error "error", I attach a screenshot of the settings and the code too
Initialize funktion
import { KeycloakService } from 'keycloak-angular'
export function initializeKeycloak(keycloak: KeycloakService) {
return () =>
keycloak.init({
config: {
url: 'http://localhost:8080',
realm: 'cld_poc',
clientId: 'keycloak-express',
},
loadUserProfileAtStartUp: true,
initOptions: {
onLoad: 'login-required',
pkceMethod: 'S256',
checkLoginIframe: false,
},
})
}
Auth guard
import { Injectable } from '@angular/core'
import {
ActivatedRouteSnapshot,
RouterStateSnapshot,
UrlTree,
Router,
} from '@angular/router'
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular'
@Injectable({
providedIn: 'root',
})
export class AuthGuard extends KeycloakAuthGuard {
constructor(
protected override readonly router: Router,
protected readonly keycloak: KeycloakService
) {
super(router, keycloak)
}
async isAccessAllowed(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean | UrlTree> {
if (!this.authenticated) {
await this.keycloak.login({
redirectUri: window.location.origin + state.url,
})
}
const requiredRoles = route.data['roles']
if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
return true
}
// return this.authenticated
return requiredRoles.every((role) => this.roles.includes(role))
}
}
router
const routes: Routes = [
{
path: '',
component: MediaLibraryComponent,
canActivate: [AuthGuard],
},
...
]
app module
@NgModule({
declarations: [
...
],
imports: [
...
KeycloakAngularModule,
],
providers: [
...
{
provide: APP_INITIALIZER,
useFactory: initializeKeycloak,
multi: true,
deps: [KeycloakService],
},
],
bootstrap: [AppComponent],
})
everything I tried I described above. I rummaged all over Google and stackoverflow in search of a problem, so I decided to write personally.
You need to assign this role to the user you are trying to log in with.