如何将自定义数据传递给HandleChallengeAsync

时间:2017-12-04 18:34:46

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

我有一个带有自定义身份验证方案的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看起来是存储此类自定义数据的好地方。但我无法弄清楚如何在AuthenticationProperties内创建HandleAuthenticateAsync对象并将其附加到AuthenticateResult对象。有办法吗?

1 个答案:

答案 0 :(得分:1)

身份验证处理程序是瞬态范围的,您可以在源代码中看到:https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication/AuthenticationBuilder.cs#L44

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

相关问题