Keycloak 401(未经授权)Angular

问题描述 投票:0回答:1

我正在尝试设置一个有角度的钥匙锁。 如果在 keycloak 管理面板中我不选择设置“访问设置”,则一切正常 " --> 我的客户端设置中的“根 URL”和“主页 URL”。 如果选择了它们,那么我会收到错误“错误”,我也附上设置和代码的屏幕截图

enter image description here

初始化功能

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,
      },
    })
}

授权守卫

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))
  }
}

路由器

const routes: Routes = [
  {
    path: '',
    component: MediaLibraryComponent,
    canActivate: [AuthGuard],
  },
...
]

应用程序模块

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    KeycloakAngularModule,
  ],
  providers: [
    ...
    {
      provide: APP_INITIALIZER,
      useFactory: initializeKeycloak,
      multi: true,
      deps: [KeycloakService],
    },
  ],
  bootstrap: [AppComponent],
})

enter image description here

我尝试过的一切都在上面描述过。 我翻遍了 Google 和 stackoverflow 来寻找问题,所以我决定亲自写一下。

angular single-sign-on keycloak http-status-code-401 keycloak-angular
1个回答
0
投票

You need to assign this role to the user you are trying to log in with

© www.soinside.com 2019 - 2024. All rights reserved.