【问题标题】:How to pass custom data to HandleChallengeAsync如何将自定义数据传递给 HandleChallengeAsync
【发布时间】:2018-05-18 07:07:51
【问题描述】:

我有一个带有自定义身份验证方案的 Web API,可以读取身份验证令牌。由于多种原因(令牌丢失、无效、过期),身份验证可能会失败(401),所以我希望能够在 HTTP 响应中指出失败的原因。例如,401 Token has expired

令牌在AuthenticationHandler<T>.HandleAuthenticateAsync 中进行解析和验证。如何将该方法的失败原因传递给HandleChallengeAsync

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
  AuthenticateResult result = null;
  var tokenResult = this.ParseToken(this.Request, out var token);

  if (tokenResult == TokenResult.Normal)
  {
    result = AuthenticateResult.Success(this.ticketFactory.CreateAuthenticationTicket(token));
  }
  else
  {
    result = AuthenticateResult.Fail("Bad token");
    // FIXME: Figure out how to populate the Properties property
    //result.Properties.Items.Add(nameof(TokenResult), tokenResult.ToString());
  }

  return Task.FromResult(result);
}

AuthenticationProperties.Items 看起来是存储此类自定义数据的好地方。但我不知道如何在HandleAuthenticateAsync 内创建AuthenticationProperties 对象并将其附加到AuthenticateResult 对象。有什么办法吗?

【问题讨论】:

    标签: c# authentication asp.net-core asp.net-core-webapi


    【解决方案1】:

    身份验证处理程序是瞬态范围的,您可以在源代码中看到:https://github.com/dotnet/aspnetcore/blob/4dd2a883a4b22cf3df5944b1224355a94158f516/src/Security/Authentication/Core/src/AuthenticationBuilder.cs#L48

    每个请求都会获得自己的处理程序实例,因此您可以将失败原因设置为实例字段。

    【讨论】:

    猜你喜欢
    • 2021-11-08
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    相关资源
    最近更新 更多