[英].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.