我目前正在设置一个带有SPA 客户端和一些 REST 服务的身份服务器来使用数据。
一切似乎都正常,但我目前很难理解,为什么每个有效的 API 调用都会access_token
触发/authorize
对身份服务器端点的请求。
登录页面上的按钮
这个按钮只是通过HttpClient
from的一个实例调用我的 REST API@angular/common/http
这些按钮在我的/login
页面上。
来自身份服务器的回调设置为转到/login/callback
。
/authorize
对端点的请求
每次单击该按钮都会向/authorize
端点发送一个请求,结果会将我通过 http 重定向302
到该/login/callback
页面。
请求仍然通过,一切正常,但总是发生这种重定向。
我本来希望在有效的情况下,access_token
不需要这个请求?
AccessToken 拦截器
在AccessTokenInterceptor
I do call myOidcService
中,可以UserManager
从oidc-client库访问。
由于某种原因,涉及到getUser()
的每个请求都会UserManager
触发该/authorize
请求作为响应——即使access_token
它仍然有效。我在这里想念什么?
@Injectable()
export class AccessTokenInterceptor implements HttpInterceptor {
constructor(private oidcService: OidcService) { }
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return this.oidcService.getUser()
.mergeMap((user: User) => {
if (user) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${user.access_token}`
}
});
}
return next.handle(request);
});
}
}
感谢您在这方面的任何帮助,如果您需要更多代码示例,请告诉我。
更新 1
一旦我调用“Call Api”按钮,就会发出以下三个请求。
OPTIONS
请求我的 REST API。/authorize
请求(最终返回一个http302
并执行我想避免的重定向)GET
请求这是我打算做的。
更新 2
Web 应用程序 - UserManagerSettings
{
"authority": "https://localhost:44327",
"client_id": "webClient",
"response_type": "id_token token",
"scope": "openid testclientapi testclientapi.read testclientapi.write",
"redirect_uri": "http://localhost:4200/login/callback",
"post_logout_redirect_uri": "http://localhost:4200/logout/callback",
"silent_redirect_uri": "http://localhost:4200/login/silentLogin",
"automaticSilentRenew": true,
"monitorSession": true,
"revokeAccessTokenOnSignout": true,
"loadUserInfo": true
}
身份服务器 - 客户端配置
new Client {
ClientId = "webClient",
ClientName = "myclient",
AllowedGrantTypes = GrantTypes.Implicit,
AccessTokenType = AccessTokenType.Reference,
AccessTokenLifetime = 60 * 60,
IdentityTokenLifetime = 30,
RequireConsent = false,
AllowOfflineAccess = true,
AllowAccessTokensViaBrowser = true,
ClientSecrets =
{
new Secret("XYZ)
},
AllowedCorsOrigins = new string[]
{
"http://localhost:4200",
},
RedirectUris =
{
"http://localhost:4200/login/callback",
"http://localhost:4200/login/silentLogin",
"http://localhost:4200/logout/callback",
},
PostLogoutRedirectUris =
{
"http://localhost:4200/logout/callback",
},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
"testclientapi",
"testclientapi.read",
"testclientapi.write"
}
}
};
更新 3
getUser() : Observable<User> {
return Observable.fromPromise(this.userManager.getUser())
}