OnAuthenticationFailed

OnAuthenticationFailed

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

问题描述

限时删除!!

我正在使用

对于状态和

未能加载响应数据

回复.

我也试过:

context.Response.WriteAsync(result).Wait();返回 Task.CompletedTask;

但结果是一样的.

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

解决方案

需要注意的是,aspnet-contrib OAuth2 验证和 MSFT JWT 处理程序都会自动返回一个 WWW-Authenticate 响应头,其中包含返回 401 响应时的错误代码/描述:

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

services.AddAuthentication().AddJwtBearer(选项=>{options.Authority = "http://localhost:54540/";options.Audience = "resource_server";options.RequireHttpsMetadata = false;options.Events = new JwtBearerEvents();options.Events.OnChallenge = 上下文 =>{//跳过默认逻辑.context.HandleResponse();var 有效载荷 = 新的 JObject{[错误"] = context.Error,[error_description"] = context.ErrorDescription,[error_uri"] = context.ErrorUri};context.Response.ContentType = "application/json";context.Response.StatusCode = 401;返回 context.Response.WriteAsync(payload.ToString());};});

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

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

for Status and

for response.

I also tried:

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

but the result is the same.

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

解决方案

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

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = 401;

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

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

1403页,肝出来的..

09-06 16:06