【问题标题】:How to customize error code in custom AuthenticationHandler如何在自定义 AuthenticationHandler 中自定义错误代码
【发布时间】:2020-08-31 03:36:01
【问题描述】:

有一个自定义的AuthenticationHandler 命名为CustomAuthenticationHandler,默认错误码是401。但是我必须在不同的情况下用不同的错误码和错误信息来响应。

如果请求在某些情况下应该响应 403 并且当前的解决方案如下所示:

public class CustomAuthenticationHandler: AuthenticationHandler<MSGraphAuthenticationOptions>
{
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (xxx) 
        {        
            var response = this.httpContextAccessor.HttpContext.Response;
            response.StatusCode = StatusCodes.Status403Forbidden;
            await response.WriteAsync("test");
            return AuthenticateResult.NoResult();
        }
    }
}

http 响应的错误代码是 403,这是预期的,但请求仍然会遇到 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)

如何在await response.WriteAsync("test"); 之后停止中间件流?

【问题讨论】:

  • 您可以尝试通过response.HasStarted检查“响应是否已经开始”。

标签: c# asp.net-core authentication asp.net-core-authenticationhandler


【解决方案1】:

如果您的身份验证失败,您应该调用AuthenticateResult.Fail("&lt;your custom message here&gt;");,这样管道的其余部分就不会被执行。

无论如何,当 Authorization 失败时返回 403 错误消息,而不是在 Authentication 失败的情况下,因此您可以按照此处所述设置您的授权策略:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/simple?view=aspnetcore-3.1

【讨论】:

  • 添加授权属性是一个很好的解决方案。但是在我们的例子中,需要在每个函数中添加该属性,所以我们最好在认证中实现它。认证流程中没有办法返回403?
  • 您可以设置默认授权策略,因此不必使用任何属性:services.AddAuthorization(options =&gt; { options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); }); 这篇文章也可能会有所帮助:andrewlock.net/…
  • HandleChallengeAsync 帮助重写 40​​1 错误代码。 docs.microsoft.com/en-us/dotnet/api/…
猜你喜欢
  • 2012-06-03
  • 1970-01-01
  • 2012-11-15
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
相关资源
最近更新 更多