【问题标题】:How to force a success and proceed with the request inside the JwtBearerEvents.OnAuthenticationFailed event如何强制成功并继续 JwtBearerEvents.OnAuthenticationFailed 事件中的请求
【发布时间】:2021-11-06 03:41:09
【问题描述】:

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

如果 JWT 身份验证出错,我需要调用第二种身份验证,如果成功,则继续调用控制器。

但是,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;
                   }
               };
           });

【问题讨论】:

    标签: c# asp.net-core jwt asp.net-core-webapi middleware


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      试试这个?

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

      【讨论】:

      • 它返回 200 但请求没有到达控制器!
      猜你喜欢
      • 2021-07-25
      • 2021-05-07
      • 2011-07-21
      • 2020-07-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多