当授权在我的API中失败时,我必须显示自定义(Json)响应体。默认情况下,我有这样的消息:未经授权。但我想返回一个包含自定义代码错误、消息和其他细节的json。这是我所做的一个例子。
o.Events = new JwtBearerEvents
{
OnChallenge = async (context) =>
{
if (!context.Request.Headers.ContainsKey("Authorization"))
{
context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "The authorization parameter is not given or the token passed is empty";
}
},
OnAuthenticationFailed = async (context) =>
{
await context.HttpContext.Response.WriteAsync("ramses");
context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "The token is invalid or has expired";
},
};
我尝试使用WriteAsync方法的HttpContext.Response,但我定义的消息没有出现,只有原因短语出现正确。
这是我的API中结果的图像。
我在startup.cs的jwtBearer配置中指定了这段代码
发布于 2022-01-27 20:15:20
我在我的代码中使用了这个,它运行得很好
.AddJwtBearer(o => {
o.RequireHttpsMetadata = false;
o.SaveToken = false;
o.TokenValidationParameters = tokenValidationParameters;
o.Events = new JwtBearerEvents {
OnAuthenticationFailed = c => {
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync(c.Exception.ToString());
},
OnChallenge = context => {
context.HandleResponse();
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
var result = JsonConvert.SerializeObject(new {
status = "un-authorized",
message = "un-authorized"
});
return context.Response.WriteAsync(result);
},
OnForbidden = context => {
context.Response.StatusCode = 403;
context.Response.ContentType = "application/json";
var result = JsonConvert.SerializeObject(new {
status = "un-authorized",
message = "un-authorized"
});
return context.Response.WriteAsync(result);
}
};
});
https://stackoverflow.com/questions/70884906
复制相似问题