如何强制成功并在 JwtBearerEvents.OnAuthenticationFailed 事件中继续请求

How to force a success and proceed with the request inside the JwtBearerEvents.OnAuthenticationFailed event

我的项目有两种认证方式,第一种是通过JWT,第二种还是会实现。

如果JWT认证出错,我需要调用第二种认证,如果成功,继续调用controller。

但是,OnAuthenticationFailed 事件的处理不起作用。

如何在 OnAuthenticationFailed 事件中强制成功?

没用

services.AddAuthentication(BearerAuthenticationDefaults.AuthenticationScheme)
           .AddJwtBearer(options =>
           {
               options.Authority = configuration.GetSection("AuthenticationConfiguration").GetValue<string>("Authority");
               options.TokenValidationParameters = new TokenValidationParameters()
               {
                   ValidateAudience = false
               };
               options.Events = new JwtBearerEvents()
               {
                   OnAuthenticationFailed = c =>
                   {
                       //here a second authentication will be implemented

                       //(if secondauthentication.IsSucess)
                       c.Exception = null;
                       c.Success();

                       return Task.CompletedTask;
                   }
               };
           });

试试这个?

options.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = c =>
                    {
                        var payload = new JObject
                        {
                            ["success"] = "ok",
                            ["error_description"] = "success"
                        };
                        c.Response.StatusCode = 200;
                        c.Response.ContentType = "text/plain";
                        return c.Response.WriteAsync(payload.ToString());
                    }
                };

Asp.net 应用程序可以有多个身份验证服务。在第一种认证失败事件中不要写第二种认证,建议将其注册为认证中间件。

例如,以下代码为 cookie 和 JWT 承载身份验证方案注册身份验证服务和处理程序:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options))
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));

更多关于身份验证的详细信息,您可以参考下面的文档:

Overview of ASP.NET Core authentication