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;
    }
};