OAuth2代码流使用angular-oauth2-oidc和Keycloak



我正试图在我的Angular项目中集成一个身份提供者(在我的情况下是Keycloak)。我正在使用"angular-oauth2-oidc">

我可以从我的"主页"重定向用户。页到"登录"。点击Keycloak的页面,通常情况下,我会将用户重定向到"登陆"页面。登录成功后的应用页面。但是,当我这样做时,当Keycloak将用户重定向到"登陆"时,我意识到访问令牌尚未设置到我的浏览器存储。页面。因此,我必须将用户重定向回"home";页,然后转到"着陆"页。页,以便在此期间令牌被设置为存储。

显然,这不是一个好的做法,我相信我在那里做错了什么。以下是我一直在编写的代码;

home.component.html

<button class="btn btn-default" (click)="login()">
Login
</button>

home.component.ts

login(): void {
this.authService.login();
}

auth.service.ts

@Injectable({ providedIn: 'root' })
export class AuthService {
constructor(private oauthService: OAuthService, private router: Router) {
this.configure();
}
authConfig: AuthConfig = {
issuer: ...
redirectUri: window.location.origin + '/home',
clientId: ...
scope: ...
responseType: 'code',
disableAtHashCheck: true
}
login(): {
this.oauthService.initCodeFlow();
}
private configure() {
this.oauthService.configure(this.authConfig);
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
if(this.hasValidToken()){
this.oauthService.setupAutomaticSilentRefresh();
this.router.navigateByUrl('/landing');
}
});
}
}

我想做的是像这样;

auth.service.ts。

@Injectable({ providedIn: 'root' })
export class AuthService {
constructor(private oauthService: OAuthService, private router: Router) {
this.configure();
}
authConfig: AuthConfig = {
issuer: ...
redirectUri: window.location.origin + '/landing',
clientId: ...
scope: ...
responseType: 'code',
disableAtHashCheck: true
}
login(): {
this.oauthService.initCodeFlow();
}
private configure() {
this.oauthService.configure(this.authConfig);
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
if(this.hasValidToken()){
this.oauthService.setupAutomaticSilentRefresh();
}
});
}
}

如有任何帮助,不胜感激。

OAuth2/OpenID进程通常本质上是异步的,例如加载发现文档可能需要大约100毫秒。从一段时间以来,Angular就有了异步应用初始化器:如果你从初始化器中返回一个承诺,Angular会等待它,直到它继续做路由之类的事情。

你可以看看我的示例实现,甚至可以尝试克隆它并根据你的Keycloak重新配置它。重要的部分如下:

一个async应用的初始化式:

export function authAppInitializerFactory(authService: AuthService): () => Promise<void> {
return () => authService.runInitialLoginSequence();
}

runInitialLoginSequence()方法与configure()方法类似,主要区别在于:

  • 它返回一个承诺(你的方法立即返回,不需要等待承诺),并让Angular等待它解析
  • 它有围绕state参数的逻辑,OIDC的方法确保用户在被要求登录
  • 之前进入他们打算去的页面

我建议查看登录顺序方法以获得灵感。(请注意,我没有在库的服务上调用.configure(...),因为我更喜欢将模块中的所有内容注册为提供者。)

最新更新