我实现了AuthenticationHandler的一个子类,它返回AuthenticationResult.Fail("This is why you can't log in"); 我本来希望这个消息在正文中结束,或者至少在HTTP状态文本中结束,但是我得到了一个空白的401响应。 有什么方法可以为ASP.NET核心中失败的身份验证尝试提供附加信息吗?
public async Task Invoke(HttpContext httpContext)
{
await this.Next(httpContext);
if (httpContext.Response.StatusCode == StatusCodes.Status401Unauthorized)
{
var authenticateResult = await httpContext.AuthenticateAsync();
if (authenticateResult.Failure != null)
{
var routeData = httpContext.GetRouteData() ?? new RouteData();
var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor());
var problemDetails = this.ProblemDetailsFactory.CreateProblemDetails(httpContext,
statusCode: httpContext.Response.StatusCode,
detail: authenticateResult.Failure.Message);
var result = new ObjectResult(problemDetails)
{
ContentTypes = new MediaTypeCollection(),
StatusCode = problemDetails.Status,
DeclaredType = problemDetails.GetType()
};
await this.Executor.ExecuteAsync(actionContext, result);
}
}
}
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace TestIdentity
{
public class CustomAuthenticationHandler<TOptions> : AuthenticationHandler<TOptions> where TOptions : AuthenticationSchemeOptions, new()
{
public CustomAuthenticationHandler(IOptionsMonitor<TOptions> options
, ILoggerFactory logger
, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
await Context.Response.WriteAsync("This is why you can't log in");
return AuthenticateResult.Fail("This is why you can't log in");
}
}
}
4条答案
按热度按时间8e2ybdfx1#
覆盖句柄质询异步:
在下面的例子中,
failReason
是我的AuthenticationHandler实现中的私有字段。我不知道这是否是传递失败原因的最佳方式。但是在我的测试中,AuthenticateResult.Fail
方法上的AuthenticationProperties
没有传递到HandleChallengeAsync
。来自文档:https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationhandler-1?view=aspnetcore-2.2
如果所讨论的身份验证方案将身份验证交互作为其请求流的一部分进行处理,则重写此方法以处理401质询问题(例如添加响应头,或者将登录页面或外部登录位置的401结果更改为302)。
图片来源:https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication/AuthenticationHandler.cs#L201
wpcxdonn2#
我在我的定制中间件中使用了这段代码来返回problemDetails响应。
ryevplcw3#
要更改正文或Http状态,可以尝试
Context.Response
。下面是一个演示代码:
piok6c0g4#
下面是通过重写
HandleChallengeAsync
方法写入失败的自定义AuthenticationHandler
的响应主体的方法: