我正在使用 dotnet core
开发 ASP Core Web API v3.1。
我正在使用 JWT token 进行身份验证。对于授权,我使用 [Authorize]
属性。
如果用户未登录(尝试访问标有 [Authorize]
属性的操作时)或用户的 token 未通过身份验证,我如何创建自己的响应。
我遇到了一个使用从默认授权属性继承的自定义授权属性的解决方案。在这个例子中,HandleUnauthorizedRequest
方法被覆盖。但是我在AuthorizeAttribute
里面没有看到这样的方法类(class)。
有没有办法创建自定义unauthorized
响应与 http 正文?
最佳答案
由于您使用的是 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供引用。默认逻辑不向响应写入任何内容(它只设置状态代码并设置一些 header )。因此,要继续使用默认逻辑并在其上添加内容,您可以使用以下内容:
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;
}
};
关于http - ASP Core API - 自定义未经授权的正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64082588/