KeyCloak登录导致无限循环。

3
我最近开始使用KeyCloak和Angular。我的KeyCloak Docker运行在端口8080上,我的Angular应用程序运行在4200上。现在当我通过浏览器访问我的应用时,我会被重定向到合适的重定向网址下的“auth/realms/...” 。到目前为止,这是预期的行为。然而,在KeyCloak登录页面加载之前,我甚至被重定向回了旧的“auth/realms/...”,但这次我的重定向网址却是刚刚设置过的旧的“auth/realms/...”。
问题似乎不是KeyCloak本身,而是我的Angular实现,因为即使我禁用了KeyCloak客户端或访问错误的客户端,我也会得到相同的行为。
现在来看一些代码。我已经按照以下方式设置了我的KeyCloakOptions:
export const keycloakOptions: KeycloakOptions = {
  config: {
    url: '/auth',
    realm: 'bookstore',
    clientId: 'bookstore-front-end'
  },
  initOptions: {
    onLoad: 'login-required',
    checkLoginIframe: false
  },
  enableBearerInterceptor: true,
  bearerExcludedUrls: ['/assets']
};

服务的初始化如下:

export class AppModule implements DoBootstrap {

  public ngDoBootstrap(appRef: ApplicationRef): void {
    keycloakService
      .init(keycloakOptions)
      .then(() => {
        console.log('[ngDoBootstrap] bootstrap app');
        appRef.bootstrap(AppComponent);
      })
      .catch(error => console.error('[ngDoBootstrap] init Keycloak failed', error));
  }
}

我怀疑我的应用程序路由与问题有关。它看起来像这样:

const routes: Routes = [
  // home route protected by auth guard
  {path: 'books', component: BooksComponent, canActivate: [AuthGuard]},

  // otherwise redirect to home
  {path: '', redirectTo: 'books', pathMatch: 'full'}
];

如果您需要任何进一步的代码,请告诉我,非常感谢您的帮助。

编辑:

我的第一个请求如下:

http://localhost:4200/auth/realms/bookstore/protocol/openid-connect/auth?client_id=bookstore-front-end&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2F&state=c530f55a-b21e-43c3-8e1c-a3beb134c9ee&response_mode=fragment&response_type=code&scope=openid&nonce=0c359787-92e7-4d6d-9578-a65da686b046

然而,我刚刚意识到在我的响应主体中,我得到了我的应用程序的index.html文件,这很奇怪。

你能展示所有请求的完整日志吗?(你的浏览器检查器可以记录它。)如果你在私人会话/窗口中尝试,是否显示登录页面?你的配置文件真的包含URL“auth”,还是这个问题的一个已编辑值?它可能缺少端口8080。 - Codo
我编辑了这篇文章。其他请求只是相同的,但重定向URL会越来越长。 - AndideBob
1个回答

4

您配置的Keycloak客户端方式,它不会重定向到Angular, 而是重定向到自身(稍微不同的URL)。请求URL中的端口号4200是一个很明显的标志。

要修复问题,请更改Keycloak配置(Angular中)。修改以下行:

  url: '/auth',

to:

  url: 'http://localhost:8080/auth',

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接