我不完全瞭解如何將OAuth2訪問令牌從promise(oidc-client-js)提供給使用Swagger-CodeGen生成的API代碼。將OAuth2訪問令牌配置爲typescript-angular2客戶端
提供常量值很容易,但如何更改以下來從oidc-client-js獲取用戶的訪問令牌?我想知道「正確」的方式。將此令牌粘貼到全局變量的某個位置很容易。
@NgModule({
imports: [
CommonModule,
ApiModule.forConfig(() => new Configuration({
accessToken: 'my-access-token' //this can also be a() => string function
}))
],
與正常OnInit的組成部分,我可以得到令牌從OIDC-客戶的UserManager的實例的承諾。讓這兩件事合在一起讓我感到困惑。一個看起來像靜態配置,另一個需要訂閱單身人士的承諾。
this.userSubscription = this.authService.getUser().subscribe((user) => {
if (user) {
this.access_token = user.access_token;
}
});
任何糾正我做錯的事情也將不勝感激。這是我使用Angular的第一個原型。
更新
應用Ben的建議,並抽出時間來了解APP_INITIALIZER(這是試驗非常稀少IMO文件)後,感覺就像矯枉過正。我與它被注射到揚鞭,CodeGen將產生打字稿,Angular2服務代碼配置類以下定義提供結束:
providers: [
AuthService,
AuthGuardService,
{
provide: Configuration,
useFactory: (authSvc: AuthService) => new Configuration({accessToken: authSvc.getAccessToken.bind(authSvc)}),
deps: [AuthService],
multi: false
}
]
我改變了我的AuthService來存儲服務的用戶的最新的access_token。從Swagger-CodeGen生成的代碼中調用getAccessToken()
方法,並返回用於HTTP標頭的最新jwt。它感覺乾淨,它的工作原理。請讓我知道如果(以及爲什麼)這是解決我的問題的錯誤方法。