http - ASP Core API - 自定义未经授权的正文

标签 http asp.net-core .net-core httpresponse unauthorized

我正在使用 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/

相关文章:

http - 如何使用 BASIC 身份验证从网站注销用户?

asp.net-core - AspNet5 - Windows 身份验证从声明中获取组名

.NET Core 中的 C# ConfigurationManager

amazon-web-services - 使用 Lambda 中的 AWS Cognito for .NET

ASP.Net Core静态文件安全(特别是图像)

http - mbed:建立网络连接后访问 SD 卡时出现 HardFault 错误

java - 来自 Java 的 HTTP POST 存在 JSON 问题

web-services - 用于监控 HTTP、TCP 等 Web 服务流量的工具

asp.net-core - 使用 ASP.NET Core 5 和 Blazor 的 CORS 策略出错

asp.net-core - 我可以覆盖 ASP.Net Core MVC 中单个 Controller 的默认操作吗