我已经使用 Angular 12.2 实现了 angular-oauth-oidc(版本 12.1.0)。我使用 Keycloak 作为 SSO 登录没有问题,但我在库中有一个奇怪的行为。
每次登录后,即使令牌已过期,方法hasValidIdToken和方法也会返回 true。hasValidAccessToken该库似乎没有验证令牌过期。
我的配置文件如下:
export const authCodeFlowConfig: AuthConfig = {
// Url of the Identity Provider
issuer: 'http://localhost:8080/auth/realms/realmname',
// URL of the SPA to redirect the user to after login
redirectUri: window.location.origin + '/landing',
// The SPA's id. The SPA is registerd with this id at the auth-server
clientId: 'client-name',
responseType: 'code',
// set the scope for the permissions the client should request
// The first four are defined by OIDC.
// Important: Request offline_access to get a refresh token
// The api scope is a usecase specific one
scope: 'openid profile email',
showDebugInformation: true,
};
我使用以下代码初始化库:
ngOnInit(): void {
this.oauthService.configure(authCodeFlowConfig);
this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
if (this.oauthService.hasValidAccessToken()) {
this.router.navigate(['home']);
}
else {
this.oauthService.initCodeFlow();
}
});
}
最后,我检查令牌是否在警卫中使用以下条件有效:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {
var hasIdToken = this.oauthService.hasValidIdToken();
var hasAccessToken = this.oauthService.hasValidAccessToken();
var hasAccess = (hasIdToken && hasAccessToken)
if (!hasAccess) {
console.log('AuthGuard: Token not valid');
this.router.navigate(['landing']);
}
else {
console.log('AuthGuard: Valid token');
}
return hasAccess;
}
true如果我以前登录,此方法总是返回。如果没有事先登录,它会false按预期返回。
如果我使用其他库进行令牌验证,则在验证过期令牌时会得到预期的结果。