简体   繁体   English

.NET 核心 3.1 OAUTH 2 自定义令牌自省 JSON 响应 - “无法设置状态代码,因为响应已经开始”

[英].NET Core 3.1 OAUTH 2 Token Introspection with Custom JSON Response - "Status Code cannot be set because the response has already started"

I have already tried all the solutions here , and nothing is working.我已经在这里尝试了所有解决方案,但没有任何效果。

I am using package IdentityModel.AspNetCore.OAuth2Introspection v6.0.0.我正在使用 package IdentityModel.AspNetCore.OAuth2Introspection v6.0.0。 The business use case I have is that I have to return a 401 Unauthorized status code plus a custom JSON object in the response when authentication fails.我的业务用例是,当身份验证失败时,我必须在响应中返回 401 Unauthorized 状态代码和自定义 JSON object This code works to return the JSON object, BUT it throws the same error on the backend each time, and once that starts happening, latency shoots up on my app.此代码用于返回 JSON object,但它每次都会在后端抛出相同的错误,一旦开始发生,我的应用程序的延迟就会激增。

Here's what I have so far:这是我到目前为止所拥有的:

services.AddAuthentication("Bearer")
    .AddOAuth2Introspection(options =>
    {
        options.Authority = _idpAuthority;
        options.ClientId = _apiResourceName;
        options.ClientSecret = _apiResourceSecret;
    
        options.Events.OnAuthenticationFailed = async context =>
        {
            context.NoResult();
            if (!context.Response.HasStarted)
            {
                context.Response.StatusCode = 401;
                context.Response.ContentType = "application/json";
                await context.Response.Body.WriteAsync(JsonSerializer.SerializeToUtf8Bytes(new ErrorListResponseModel().AddError("401", "UNAUTHORIZED")));     
            }
                               
        };
    });

This produces the error:这会产生错误:

System.InvalidOperationException: StatusCode cannot be set because the response has already started. System.InvalidOperationException:无法设置 StatusCode,因为响应已经开始。

The logging callsite of this error is Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ReportApplicationError .此错误的日志调用站点是Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ReportApplicationError

Whether I add or remove context.NoResult() -- no difference.无论我添加还是删除context.NoResult() - 都没有区别。

I've tried using a synchronous delegate function and returning Task.CompletedTask instead -- no difference.我试过使用同步委托 function 并返回Task.CompletedTask没有区别。

If I don't explicitly set the context.Response.StatusCode , I get a 200 status code in the response, AND the error still throws!如果我没有明确设置context.Response.StatusCode ,我会在响应中得到一个200状态代码,并且错误仍然会抛出!

The remarks in the library suggest that图书馆的言论表明

Invoked if exceptions are thrown during request processing.如果在请求处理期间抛出异常,则调用。 The exceptions will be re-thrown after this event unless suppressed.除非被抑制,否则将在此事件后重新抛出异常。

. . . . . . but I don't see any suggestions on how to suppress these exceptions.但我没有看到任何关于如何抑制这些异常的建议。

Please help请帮忙

I resolved this by taking this code out of the OnAuthenticationFailed event and moving it into the Configure(IApplicationBuilder app) part of Startup.cs:我通过将此代码从OnAuthenticationFailed事件中取出并将其移至 Startup.cs 的Configure(IApplicationBuilder app)部分来解决此问题:

app.UseStatusCodePages((StatusCodeContext statusCodeContext) =>
{
    var context = statusCodeContext.HttpContext;
    if (context.Response.StatusCode == 401)
    {
        context.Response.ContentType = _applicationJsonMediaHeader;
        return context.Response.Body.WriteAsync(_serializedUnauthorizedError).AsTask();
    }

    return Task.CompletedTask;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.Net Core 中间件无法设置异常状态码,因为“响应已经开始” - ASP.Net Core middleware cannot set status code on exception because "response has already started" ASP.Net core JWT Bearer authentication with Keycloak StatusCode 无法设置,因为响应已经开始 - ASP.Net core JWT Bearer authentication with Keycloak StatusCode cannot be set because the response has already started Azure 功能:无法设置StatusCode 因为响应已经开始 - Azure Functions: StatusCode cannot be set because the response has already started 在 dot net core API 中设置具有相同状态响应的自定义错误代码 - Set custom error code with same status response in dot net core API 带有自定义响应包装器的 ASP.NET Core 3.1 Web API 中的 JSON 响应中断 - JSON response breaks in ASP.NET Core 3.1 Web API with custom response wrapper 准ASP.NET Core中间件项目中的“响应已经开始”异常 - “Response has already started” exception in a bare-bones ASP.NET Core middleware project 如何在 ASP.NET Core 3.1 中为 HTTP 状态 415 创建自定义响应? - How to create a custom response for HTTP status 415 in ASP.NET Core 3.1? .Net核心JWT自定义过期令牌响应 - .Net core JWT Custom Expired Token Response 服务器端 .NET Core 中的 Session.SetString() 产生错误“响应开始后无法建立会话” - Session.SetString() in Server Side .NET Core Produces error "The session cannot be established after the response has started" .net会话状态已创建一个会话ID,但无法保存它,因为该响应已被应用程序刷新 - .net Session state has created a session id, but cannot save it because the response was already flushed by the application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM