我最近开始在Angular中使用KeyCloak。我的KeyCloak Docker在端口8080上运行,而我的Angular-Application在4200上运行。现在,当我通过浏览器访问我的应用程序时,将auth/realms/...
使用适当的redirect-url 重定向到。到目前为止,这就是预期的行为。但是,即使在加载KeyCloak登录页面之前,我也被重定向回auth/realms/...
,但是这次我的redirect-url是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
应用程序的文件,这很奇怪。
您配置Keycloak客户端的方式永远不会重定向到Angular。相反,它重定向到自身(URL稍有不同)。请求的URL中的端口号4200是赠品。
要解决此问题,请更改Keycloak配置(在Angular中)。换线
url: '/auth',
至:
url: 'http://localhost:8080/auth',
哦,伙计...谢谢!那成功了...