1

有一个自定义的 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,这是预期的,但是reqeust仍然会遇到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");

4

1 回答 1

0

如果您的身份验证失败,您应该调用AuthenticateResult.Fail("<your custom message here>");以便管道的其余部分不会被执行。

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

于 2020-08-31T11:29:34.870 回答