首页 > 解决方案 > 令牌刷新时向 IdentityServer 发送自定义参数

问题描述

更新/刷新令牌时是否可以将自定义参数传递给身份服务器?

在我的例子中,我有 identityserver4 和一个带有 oidc-client 框架的 Angular 客户端,其中客户端使用来自 OAuth2 和 OpenIdConnect 的 PKCE 的代码流登录身份。

这个应用程序的想法是能够在同一个程序但在不同公司的同一用户登录,因此,当用户更改公司时,他将不得不刷新令牌以获得该公司的不同角色。

目前,当客户端通过引入他的凭据以身份登录时,他通过以下方式从 Angular 客户端传递公司:

  private _authNavStatusSource = new BehaviorSubject<boolean>(false);

  authNavStatus$ = this._authNavStatusSource.asObservable();

  private manager = new UserManager(getClientSettings());
  user: User | null;

  public httpOptions;

  constructor(private http: HttpClient, private configService: ConfigService) {
    super();

    this.manager.getUser().then(user => {
      this.user = user;
      this._authNavStatusSource.next(this.isAuthenticated());
    });

    this.manager.events.addUserLoaded(user => {
      this.user = user;
    });

    this.subscribeevents();

  }

  login(company: string) {
    this.manager.settings.extraQueryParams = {companyCode: company};
    return this.manager.signinRedirect();
  }

  async completeAuthentication() {
      this.user = await this.manager.signinRedirectCallback();
      this._authNavStatusSource.next(this.isAuthenticated());
      console.log('Login complete');
  }

...

  async signout() {
    await this.manager.signoutRedirect();
  }

这样,在 Identity Server AccountController 中,我可以从以下位置访问此参数:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string button)
{

var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

…

Claim[] additionalLocalClaims =
    {
       new Claim("companyCode", context.Parameters["companyCode"])
    };

var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

Claim[] additionalLocalClaims =
    {
       new Claim("companyCode", context.Parameters["companyCode"])
    };

…
await HttpContext.SignInAsync(user.SubjectId, user.UserName, props,additionalLocalClaims);

然后我向公司添加此声明,使其在我的 CustomProfileConfiguration 中可用

通过这种方式,我可以从 CustomProfileConfiguration 访问公司,并且可以获得该用户在该公司中的角色。

public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
    var companyCode = context.Subject.Claims.FirstOrDefault(c => c.Type == "companyCode");

当用户更改公司并且必须刷新令牌以承担新公司的新角色时,问题就出现了。

如果在客户端执行以下signout()方法,则用户将完全注销并进入另一家公司,他必须重新输入凭据(这将与他已经输入的凭据相同)。

目标是通过将新公司传递给身份服务器来刷新令牌,而无需使用身份服务器创建的 cookie 再次引入凭据。

我希望我能很好地解释自己,你能帮助我,非常感谢!

标签: angularauthenticationidentityserver4openidopenid-connect

解决方案


推荐阅读