gpt4 book ai didi

asp.net-core - 使用 UseJwtBearerAuthentication 中间件自定义 401 和 403 响应模型

转载 作者:行者123 更新时间:2023-12-02 05:03:04 24 4
gpt4 key购买 nike

当 401 和 403 发生时,我想使用 JSON 响应模型进行响应。例如:

HTTP 401
{
"message": "Authentication failed. The request must include a valid and non-expired bearer token in the Authorization header."
}

我正在使用中间件(如 this answer 中的建议)来拦截 404,效果很好,但 401 或 403 的情况并非如此。这是中间件:

app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 401)
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(UnauthorizedModel.Create(), SerializerSettings), Encoding.UTF8);
}
});

当放置在 Startup.Configure(..) 中的 app.UseJwtBearerAuthentication(..) 下面时,它似乎被完全忽略并返回正常的 401。

当放置在 Startup.Configure(..) 中的 app.UseJwtBearerAuthentication(..) 上方时,会引发以下异常:

Connection id "0HKT7SUBPLHEM": An unhandled exception was thrown by the application. System.InvalidOperationException: Headers are read-only, response has already started. at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item(String key, StringValues value) at Microsoft.AspNetCore.Http.Internal.DefaultHttpResponse.set_ContentType(String value) at MyProject.Api.Startup.<b__12_0>d.MoveNext() in Startup.cs

最佳答案

Set 走在正确的轨道上,但实际上不需要创建自己的中间件,因为您可以利用事件模型来覆盖默认的质询逻辑。

下面是一个示例,它将返回一个 401 响应,其中包含纯文本形式的 OAuth2 错误代码/描述(您当然可以返回 JSON 或任何您想要的内容):

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = "http://localhost:54540/",
Audience = "http://localhost:54540/",
RequireHttpsMetadata = false,
Events = new JwtBearerEvents
{
OnChallenge = async context =>
{
// Override the response status code.
context.Response.StatusCode = 401;

// Emit the WWW-Authenticate header.
context.Response.Headers.Append(
HeaderNames.WWWAuthenticate,
context.Options.Challenge);

if (!string.IsNullOrEmpty(context.Error))
{
await context.Response.WriteAsync(context.Error);
}

if (!string.IsNullOrEmpty(context.ErrorDescription))
{
await context.Response.WriteAsync(context.ErrorDescription);
}

context.HandleResponse();
}
}
});

或者,您也可以使用状态代码页中间件,但对于 403 响应,您不会得到任何有关导致它的授权策略的提示:

app.UseStatusCodePages(async context =>
{
if (context.HttpContext.Request.Path.StartsWithSegments("/api") &&
(context.HttpContext.Response.StatusCode == 401 ||
context.HttpContext.Response.StatusCode == 403))
{
await context.HttpContext.Response.WriteAsync("Unauthorized request");
}
});

关于asp.net-core - 使用 UseJwtBearerAuthentication 中间件自定义 401 和 403 响应模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38281116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com