gpt4 book ai didi

asp.net-core - AddJwtBearer OnAuthenticationFailed 返回自定义错误

转载 作者:行者123 更新时间:2023-12-04 16:45:34 25 4
gpt4 key购买 nike

我正在使用 Openidict .
我正在尝试使用自定义状态代码返回自定义消息,但我无法做到。我在 startup.cs 中的配置:

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.Authority = this.Configuration["Authentication:OpenIddict:Authority"];
o.Audience = "MyApp"; //Also in Auhorization.cs controller.
o.RequireHttpsMetadata = !this.Environment.IsDevelopment();
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = context =>
{
context.Response.StatusCode = HttpStatusCodes.AuthenticationFailed;
context.Response.ContentType = "application/json";
var err = this.Environment.IsDevelopment() ? context.Exception.ToString() : "An error occurred processing your authentication.";
var result = JsonConvert.SerializeObject(new {err});
return context.Response.WriteAsync(result);
}
};
});

但问题是没有返回任何内容。 Chrome 开发者工具报告

(failed)



error

状态和

Failed to load response data



error

为回应。

我也试过:
context.Response.WriteAsync(result).Wait();
return Task.CompletedTask;

但结果是一样的。

期望的行为:
我想返回带有错误消息的自定义状态代码。

最佳答案

面临同样的问题,尝试了 Pinpoint 提供的解决方案,但它在 ASP.NET core 2.0 上对我不起作用。但是基于 Pinpoint 的解决方案和一些反复试验,以下代码对我有用。

var builder = services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.Authority = "http://192.168.0.110/auth/realms/demo";
o.Audience = "demo-app";
o.RequireHttpsMetadata = false;

o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
c.Response.WriteAsync(c.Exception.ToString()).Wait();
return Task.CompletedTask;
},
OnChallenge = c =>
{
c.HandleResponse();
return Task.CompletedTask;
}
};
});

关于asp.net-core - AddJwtBearer OnAuthenticationFailed 返回自定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649717/

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