Angular-默认情况下,Keycloak 没有将不记名令牌添加到我的 http 请求中
Angular-Keycloak is not adding the bearer token by default to my http requests
我正在尝试实施 keycloak-angular,但我无法将不记名令牌默认添加到我的 http 请求中。
"keycloak-angular": "9.1.0"
“keycloak-js”:“16.0.0”
"Angular": "13.0.2"
function initializeKeycloak(keycloak: KeycloakService) {
return async () =>
await keycloak.init({
config: {
url: 'https://127.0.0.1:8443/auth',
realm: '*****',
clientId: '****',
},
initOptions: {
onLoad: 'login-required',
checkLoginIframe: false,
},
loadUserProfileAtStartUp: true,
enableBearerInterceptor: true,
bearerExcludedUrls: [],
bearerPrefix:'Bearer '
});
}
@NgModule({
declarations: [
AppComponent,
],
imports: [
CoreModule,
BrowserModule,
KeycloakAngularModule,
AppRoutingModule
],
providers: [
{ provide: LOCALE_ID, useValue: 'it' },
{
provide: APP_INITIALIZER,
useFactory: initializeKeycloak,
multi: true,
deps: [KeycloakService]
},
],
bootstrap: [AppComponent]
})
您必须使用 HttpInterceptor 在每次 api 调用时添加自定义 headers。
创建拦截器,并将其添加到 AppModule
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: ApiInterceptor,
multi: true,
}
],
实现拦截功能:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer #YOUR_TOKEN_HERE#`
}
});
return next.handle(request);
}
我正在尝试实施 keycloak-angular,但我无法将不记名令牌默认添加到我的 http 请求中。
"keycloak-angular": "9.1.0" “keycloak-js”:“16.0.0” "Angular": "13.0.2"
function initializeKeycloak(keycloak: KeycloakService) {
return async () =>
await keycloak.init({
config: {
url: 'https://127.0.0.1:8443/auth',
realm: '*****',
clientId: '****',
},
initOptions: {
onLoad: 'login-required',
checkLoginIframe: false,
},
loadUserProfileAtStartUp: true,
enableBearerInterceptor: true,
bearerExcludedUrls: [],
bearerPrefix:'Bearer '
});
}
@NgModule({
declarations: [
AppComponent,
],
imports: [
CoreModule,
BrowserModule,
KeycloakAngularModule,
AppRoutingModule
],
providers: [
{ provide: LOCALE_ID, useValue: 'it' },
{
provide: APP_INITIALIZER,
useFactory: initializeKeycloak,
multi: true,
deps: [KeycloakService]
},
],
bootstrap: [AppComponent]
})
您必须使用 HttpInterceptor 在每次 api 调用时添加自定义 headers。 创建拦截器,并将其添加到 AppModule
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: ApiInterceptor,
multi: true,
}
],
实现拦截功能:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer #YOUR_TOKEN_HERE#`
}
});
return next.handle(request);
}