C# 如何在自定义AuthenticationHandler中自定义错误代码
有一个名为C# 如何在自定义AuthenticationHandler中自定义错误代码,c#,asp.net-core,authentication,asp.net-core-authenticationhandler,C#,Asp.net Core,Authentication,Asp.net Core Authenticationhandler,有一个名为CustomAuthenticationHandler的自定义AuthenticationHandler,默认错误代码为401。但在不同的条件下,我必须用不同的错误代码和错误消息进行响应 如果请求在某些情况下响应403,当前解决方案如下所示: 公共类CustomAuthenticationHandler:AuthenticationHandler { 受保护的重写异步任务handleAuthenticateAync() { if(xxx) { var response=
CustomAuthenticationHandler
的自定义AuthenticationHandler,默认错误代码为401。但在不同的条件下,我必须用不同的错误代码和错误消息进行响应
如果请求在某些情况下响应403,当前解决方案如下所示:
公共类CustomAuthenticationHandler:AuthenticationHandler
{
受保护的重写异步任务handleAuthenticateAync()
{
if(xxx)
{
var response=this.httpContextAccessor.HttpContext.response;
response.StatusCode=StatusCodes.status403禁止;
等待响应。WriteAsync(“测试”);
返回AuthenticateResult.NoResult();
}
}
}
http响应的错误代码为403,这是预期的,但Request仍会运行到next()
,并且会抛出错误:
System.InvalidOperationException: StatusCode cannot be set because the response has already started.
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ThrowResponseAlreadyStartedException(String name)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.Microsoft.AspNetCore.Http.Features.IHttpResponseFeature.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Http.DefaultHttpResponse.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.HandleChallengeAsync(AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.ChallengeAsync(AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.Management.Services.CloudPC.Api.Middlewares.MetricsMiddleware.InvokeAsync(HttpContext context, ILoggerX logger)
如何在
等待响应后停止中间包流。WriteAsync(“test”)代码>?如果身份验证失败,则应调用AuthenticateResult.Fail(“”)代码>因此管道的其余部分不会被执行
无论如何,403错误消息在授权失败时返回,而不是在身份验证失败的情况下返回,因此您可以按此处所述设置授权策略:如果您的身份验证失败,您应该调用AuthenticateResult.fail(“”)代码>因此管道的其余部分不会被执行
不管怎样,当授权失败时返回403错误消息,而不是在身份验证失败的情况下,因此,您可以按此处所述设置授权策略:您可以尝试通过response.HasStarted
检查“响应是否已启动”。您可以尝试通过response.HasStarted
检查“响应是否已启动”。添加授权属性是一个很好的解决方案。但是在我们的例子中,属性需要添加到每个函数中,因此我们最好在身份验证中实现它。无法在身份验证流中返回403?您可以设置默认授权策略,以便不必使用任何属性:services.AddAuthorization(options=>{options.DefaultPolicy=new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();})代码>本文可能也会有所帮助:HandleChallengeAsync
帮助重写401错误代码。添加authorize属性是一个很好的解决方案。但是在我们的例子中,属性需要添加到每个函数中,因此我们最好在身份验证中实现它。无法在身份验证流中返回403?您可以设置默认授权策略,以便不必使用任何属性:services.AddAuthorization(options=>{options.DefaultPolicy=new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();})代码>本文可能也会有所帮助:HandleChallengeAsync
帮助重写401错误代码。