【发布时间】: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