首页 > 解决方案 > 让 angular-oauth2-oidc 从其他选项卡检索访问令牌

问题描述

我将angular-oauth2-oidc库与隐式流(带有 IdentityServer4 服务器)结合使用。我已经成功设置了文档中的静默刷新建议

这是我在包装服务中引导事物的方式:

private userSubject = new Subject<User>();

constructor(private config: ConfigService, private oAuthService: OAuthService)
{ }

// Called on app load:
configure(): void {
    const config: AuthConfig = {
      issuer: this.config.getIdentityUrl(),
      logoutUrl: this.config.getIdentityUrl() + '/connect/endsession',
      redirectUri: window.location.origin + '/',
      silentRefreshRedirectUri: window.location.origin + '/silent-refresh.html',
      clientId: 'my_client_id',
      scope: 'openid profile my_api',
      sessionChecksEnabled: true,
    };

    this.oAuthService.configure(config);
    this.oAuthService.tokenValidationHandler = new JwksValidationHandler();

    this.oAuthService
      .loadDiscoveryDocumentAndLogin()
      .then((_) => this.loadUserProfile());

    this.oAuthService.setupAutomaticSilentRefresh();
}

private loadUserProfile() {
  this.oAuthService.loadUserProfile()
    .then((userProfile) => {
      const user = new User(userProfile['name']);
      this.userSubject.next(user);
    });
}

但是,如果我在新选项卡中打开应用程序,用户也会被重定向到 IdentityServer(并立即返回我的应用程序)。

我的问题:我可以让图书馆从同源的其他选项卡中检索现有的访问令牌(以及可选的用户信息),以防止重定向?(首选,因为它不需要 Ajax 调用。)

或者,在我们将某人发送到 IdentityServer 之前,是否有一种简单的方法可以尝试使用静默刷新机制?

标签: angulartypescriptidentityserver4angular-oauth2-oidc

解决方案


sessionStorage首先:我不知何故得到了适合代币的想法,并且localStorage应该始终避免。但这是来自另一个涉及更强大(刷新)令牌的项目,并且通过隐式流程,我只有短暂的访问令牌,因此localStorage也不sessionStorage. 最后:根据您自己的具体情况评估攻击媒介:“这取决于”。

我没有提到我有这个想法,而另一个答案帮助我重新思考事情并考虑使用 localStorage。这实际上是一个很好的解决方案。

事实证明,该库已内置支持localStorage用作令牌和其他数据的后备存储。起初虽然我在尝试:

// This doesn't work properly though, read on...
this.oAuthService.setStorage(localStorage);

但是这种引导方式不适用于我的情况,请参阅库 GitHub 问题列表中的问题 321 以获取我的登录信息。从该线程重复解决方案(或解决方法?),我通过在应用程序模块中执行此操作解决了问题providers

{ provide: OAuthStorage, useValue: localStorage },

现在库将正确使用 localStorage 并且新选项卡(甚至新窗口)将自动选择它。


作为脚注,如果您出于安全原因不想使用localStorage,您也可以提供自己的存储,只要它实现OAuthStorage接口即可。然后,您自己的实现可以使用任何可用的选项卡间通信技术来“询问”来自其他选项卡的数据,如果需要,可以回退到 sessionStorage。


推荐阅读