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

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

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

token 在 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目的。有办法吗?

最佳答案

身份验证处理程序是 transient 范围的,如您在此处的源代码中所见:https://github.com/dotnet/aspnetcore/blob/4dd2a883a4b22cf3df5944b1224355a94158f516/src/Security/Authentication/Core/src/AuthenticationBuilder.cs#L48

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

关于c# - 如何将自定义数据传递给 HandleChallengeAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47639777/

相关文章:

c# - 在 C# 中捕获 native C++ 异常

c# - childCount 始终为 0

c# - Azure 中的 ASP.Net 应用程序缓存 "Web App"

email - 没有通配符 SPF 记录的站点是否容易受到子域欺骗攻击?

oracle - 如何在 OCILogon2 上设置超时?

c# - mailkit imap 客户端 Inbox.MoveTo "The folder is not currently open in read-write mode."

angular - firebase.auth().currentUser 为空

c# - 从 Main 开始的类中的 iLogger

node.js - Microsoft.AspNetCore.SpaServices由于 Node 模块map.d.ts而失败

c# - 更新 .NET Standard 库以使用 ASP.NET Core 2.2 和 3.0