首页 > 解决方案 > Angular 6 和 keycloak-angular 模块:如何从服务器加载 keycloak url

问题描述

我在 Angular 6 项目中使用 keycloak-angular 模块(v 4.0.0)。现在我正在尝试从我的服务器将 Url 加载到 Keycloak 以使用(因为它可能因 apiKey 而异)。所以,在应用初始化函数中,我尝试过这样的事情:

export function initializer(keycloak: KeycloakService, http: HttpClient): () => Promise<any> {
  return () => new Promise<boolean>((resolve) => {
    const apiKey = 'myapikey;
    // TODO: make KeycloakBearerInterceptor not intercept the HTTP-Call
    // load configuration from server
    const promise = http.get<ApiConfiguration>(environment.apiHost + '/1.0/configuration?apiKey=' + apiKey).toPromise()
      .then((data: ApiConfiguration) => {

        const keycloakConfig = {
          url: data.idpConfig.authority,   <-- This comes from the server
          realm: 'mediakey',
          clientId: 'mediakey'
        };
        keycloak.init({
          config: {
            url: data.idpConfig.authority,
            realm: 'mediakey',
            clientId: 'mediakey'
          },
          loadUserProfileAtStartUp: true,
          initOptions: {
            onLoad: 'check-sso',
            // onLoad: 'login-required',
            checkLoginIframe: false,
            flow: 'implicit'
          },
          enableBearerInterceptor: false,
          bearerExcludedUrls: [
            '/assets',
            '/1.0/configuration'
          ],
        }).catch((reason) => console.log(reason));
        return true;
      });

    return promise;
  });
}

但是 KeycloakBearerInterceptor 会拦截 http-call,因为默认值为enableBearerInterceptoris true。当然,keycloak-module 还没有初始化,因此拦截器失败了

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'authenticated' of undefined
TypeError: Cannot read property 'authenticated' of undefined
    at KeycloakBearerInterceptor.push../shared/core/rest/keycloak-bearer-interceptor.ts.KeycloakBearerInterceptor.intercept (keycloak-bearer-interceptor.ts:42)

我也尝试过对 keycloak 模块进行虚拟初始化,但它始终执行 onload 功能,并且也无法禁用。

有没有人知道如何实现这一目标?谢谢

标签: angularkeycloakkeycloak-services

解决方案


事实证明,我们有一个我们自己的 KeycloakBearerInterceptor,它会启动并失败。所以这与 keycloak-angular 库无关。


推荐阅读