AddJwtBearer OnAuthenticationFailed返回自定义错误 [英] AddJwtBearer OnAuthenticationFailed return custom error

查看:1454
本文介绍了AddJwtBearer OnAuthenticationFailed返回自定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Openidict .
我试图返回带有自定义状态代码的自定义消息,但是我无法做到这一点.我在startup.cs中的配置:

I am using Openidict.
I am trying to return custom message with custom status code, but I am unable to do it. My configuration in startup.cs:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.Authority = this.Configuration["Authentication:OpenIddict:Authority"];
                o.Audience = "MyApp";           //Also in Auhorization.cs controller.
                o.RequireHttpsMetadata = !this.Environment.IsDevelopment();
                o.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = context =>
                    {
                        context.Response.StatusCode = HttpStatusCodes.AuthenticationFailed;
                        context.Response.ContentType = "application/json";
                        var err = this.Environment.IsDevelopment() ? context.Exception.ToString() : "An error occurred processing your authentication.";
                        var result = JsonConvert.SerializeObject(new {err});
                        return context.Response.WriteAsync(result);
                    }
                };
            });

但是问题是没有内容返回. Chrome开发者工具报告

But the problem is no content is returned. Chrome developer tools report

(失败)

状态和

无法加载响应数据

Failed to load response data

以获取答复.

我也尝试过:

context.Response.WriteAsync(result).Wait();
return Task.CompletedTask;

但结果是相同的.

期望的行为:
我想返回自定义状态代码和错误消息.

Desired behaviour:
I would like to return custom status code with message what went wrong.

推荐答案

请务必注意,aspnet-contrib OAuth2验证和MSFT JWT处理程序会自动返回WWW-Authenticate响应标头,其中包含错误代码/说明.返回401响应:

It's important to note that both the aspnet-contrib OAuth2 validation and the MSFT JWT handler automatically return a WWW-Authenticate response header containing an error code/description when a 401 response is returned:

如果您认为标准行为不够方便,则可以使用事件模型来手动处理挑战.例如:

If you think the standard behavior is not convenient enough, you can use the events model to manually handle the challenge. E.g:

services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.Authority = "http://localhost:54540/";
        options.Audience = "resource_server";
        options.RequireHttpsMetadata = false;
        options.Events = new JwtBearerEvents();
        options.Events.OnChallenge = context =>
        {
            // Skip the default logic.
            context.HandleResponse();

            var payload = new JObject
            {
                ["error"] = context.Error,
                ["error_description"] = context.ErrorDescription,
                ["error_uri"] = context.ErrorUri
            };

            return context.Response.WriteAsync(payload.ToString());
        };
    });

这篇关于AddJwtBearer OnAuthenticationFailed返回自定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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