ASP Core API-自定义未经授权的主体 [英] ASP Core API - Custom Unauthorized body

查看:113
本文介绍了ASP Core API-自定义未经授权的主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 dotnet core v3.1开发ASP Core Web API.

I'm developing ASP Core Web API using dotnet core v3.1.

我正在使用JWT令牌进行身份验证.对于授权,我使用 [Authorize] 属性.

I'm using JWT tokens for authentication. And for authorization I use the [Authorize] attribute.

如果用户未登录(尝试访问带有 [Authorize] 属性标记的操作)或用户的令牌未通过身份验证,如何创建自己的响应.

How can I create my own response if the user is not logged in (while trying to access the action marked with the [Authorize] attribute) or the user's token is not authenticated.

我遇到了一个使用自定义授权属性的解决方案,该属性从默认属性继承而来.在此示例中, HandleUnauthorizedRequest 方法被覆盖.但是我在 AuthorizeAttribute 类中看不到这样的方法.

I came across a solution using a custom authorization attribute inherited from the default one. And in this example, the HandleUnauthorizedRequest method is overridden. But I don't see such a method inside the AuthorizeAttribute class.

是否可以使用http正文创建自定义的未经授权的响应?

Is there a way to create custom unauthorized responses with http body?

推荐答案

由于您使用的是JWT承载身份验证,一种覆盖默认质询逻辑(执行以处理401未经授权的问题)的方法是将处理程序挂接到< Startup.ConfigureServices 中的code> JwtBearerEvents.OnChallenge 回调:

Since you are using JWT bearer authentication, one way to override the default Challenge logic (which executes to handle 401 Unauthorized concerns) is to hook a handler to the JwtBearerEvents.OnChallenge callback in 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 中的默认质询逻辑,您可以在其中找到

This will override the default challenge logic in JwtBearerHandler.HandleChallengeAsync, which you can find here for reference purposes.

默认逻辑不写入任何内容来响应(它仅设置状态代码并设置一些标头).因此,要继续使用默认逻辑并在其之上添加内容,您可以使用以下内容:

The default logic does not write any content to response (it only sets the status code and set some headers). So to keep using the default logic and add content on top of it, you can use something like this:

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

这篇关于ASP Core API-自定义未经授权的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆