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

len*_*est 6 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);
}
Run Code Online (Sandbox Code Playgroud)

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

juu*_*nas 4

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

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

  • 在处理程序类上添加一个字段,从 HandleAuthenticateAsync 分配它并从 HandleChallengeAsync 使用它。 (2认同)