如何解决ASP Core API-自定义未经授权的主体
我正在使用o = JSON.parse(j)
JSON.parse!(o[:foo])
v3.1开发ASP Core Web API。
我正在使用JWT令牌进行身份验证。为了获得授权,我使用了dotnet core
属性。
如果用户未登录(尝试访问带有[Authorize]
属性标记的操作)或用户的令牌未通过身份验证,如何创建自己的响应。
我遇到了一个使用自定义授权属性的解决方案,该属性从默认属性继承而来。在此示例中,[Authorize]
方法被覆盖。但我在HandleUnauthorizedRequest
类中看不到这样的方法。
是否可以使用http正文创建自定义AuthorizeAttribute
响应?
解决方法
由于您使用的是JWT承载身份验证,一种覆盖默认质询逻辑(执行处理401未经授权的关注)的方法是将处理程序挂接到JwtBearerEvents.OnChallenge
中的Startup.ConfigureServices
回调中:>
services.AddAuthentication().AddJwtBearer(options =>
{
// Other configs...
options.Events = new JwtBearerEvents
{
OnChallenge = async context =>
{
// Call this to skip the default logic and avoid using the default response
context.HandleResponse();
// Write to the response in any way you wish
context.Response.StatusCode = 401;
context.Response.Headers.Append("my-custom-header","custom-value");
await context.Response.WriteAsync("You are not authorized! (or some other custom message)");
}
};
});
这将覆盖JwtBearerHandler.HandleChallengeAsync
中的默认质询逻辑,您可以找到here作为参考。
默认逻辑不写入任何内容来响应(它仅设置状态代码并设置一些标头)。因此,要继续使用默认逻辑并在其之上添加内容,您可以使用以下内容:
options.Events = new JwtBearerEvents
{
OnChallenge = context =>
{
context.Response.OnStarting(async () =>
{
// Write to the response in any way you wish
await context.Response.WriteAsync("You are not authorized! (or some other custom message)");
});
return Task.CompletedTask;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。