gpt4 book ai didi

ASP.NET Core - 从 AuthenticationHandler 获取消息

转载 作者:行者123 更新时间:2023-12-03 14:38:52 25 4
gpt4 key购买 nike

我已经实现了 AuthenticationHandler 的子类.它返回 AuthenticationResult.Fail("This is why you can't log in");
我本来希望这条消息最终出现在正文中,或者至少出现在 HTTP 状态文本中,但我得到的是一个空白的 401 响应。

有没有办法为 ASP.NET 核心中的失败身份验证尝试提供附加信息?

最佳答案

覆盖 HandleChallengeAsync:

在下面的示例中 failReason是我的 AuthenticationHandler 实现中的一个私有(private)字段。
我不知道这是否是传递失败原因的最佳方式。但是 AuthenticationPropertiesAuthenticateResult.Fail方法未能通过 HandleChallengeAsync在我的测试中。

public class CustomAuthenticationHandler<TOptions> : AuthenticationHandler<TOptions> where TOptions : AuthenticationSchemeOptions, new()
{
private string failReason;

public CustomAuthenticationHandler(IOptionsMonitor<TOptions> options
, ILoggerFactory logger
, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { }

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
failReason = "Reason for auth fail";
return AuthenticateResult.Fail(failReason);
}

protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
Response.StatusCode = 401;

if (failReason != null)
{
Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = failReason;
}

return Task.CompletedTask;
}
}

来自文档: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationhandler-1?view=aspnetcore-2.2

Override this method to deal with 401 challenge concerns, if an authentication scheme in question deals an authentication interaction as part of it's request flow. (like adding a response header, or changing the 401 result to 302 of a login page or external sign-in location.)



来源:
https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication/AuthenticationHandler.cs#L201

关于ASP.NET Core - 从 AuthenticationHandler 获取消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55834452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com