From 39fe5a69e611222cfa7c4a1bcb5c23f2b0def6f1 Mon Sep 17 00:00:00 2001 From: hjhan Date: Mon, 27 Apr 2026 11:35:41 +0800 Subject: [PATCH] =?UTF-8?q?fix(auth):=20=E8=A7=A3=E5=86=B3AJAX=E8=AF=B7?= =?UTF-8?q?=E6=B1=82401=E6=9C=AA=E6=8E=88=E6=9D=83=E5=A4=84=E7=90=86?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将全局AJAX 401处理逻辑从main.js移至_MainLayout.cshtml - 移除main.js中的重复401状态检查代码 - 在Cookie认证配置中添加自定义重定向事件处理 - 优化中间件中AJAX请求检测逻辑,支持多种请求类型判断 - 更新依赖注入和服务注册中的命名空间引用 - 添加日志管理器相关引用和配置优化 --- YLErpWeb/Middleware/RefreshTokenMiddleware.cs | 10 +++- YLErpWeb/Program.cs | 46 +++++++++++++++---- YLErpWeb/Views/Shared/_MainLayout.cshtml | 9 ++++ YLErpWeb/wwwroot/Scripts/base/main.js | 8 ---- 4 files changed, 54 insertions(+), 19 deletions(-) diff --git a/YLErpWeb/Middleware/RefreshTokenMiddleware.cs b/YLErpWeb/Middleware/RefreshTokenMiddleware.cs index 7b51d56a..a0d9f55c 100644 --- a/YLErpWeb/Middleware/RefreshTokenMiddleware.cs +++ b/YLErpWeb/Middleware/RefreshTokenMiddleware.cs @@ -29,16 +29,22 @@ namespace YLErp.Web.Middleware } /// - /// 统一拒绝请求:清除Cookie并跳转登录页或返回401 + /// 统一拒绝请求:清除Cookie并返回401或跳转登录页 /// private static void RejectRequest(HttpContext context) { context.Response.Cookies.Delete("Access-Token"); context.Response.Cookies.Delete("Access-Token-Encrypt"); - if (context.Request.Headers["X-Requested-With"] == "XMLHttpRequest") + var isAjax = context.Request.Headers["X-Requested-With"] == "XMLHttpRequest" || + !context.Request.Headers["Accept"].ToString().Contains("text/html"); + if (isAjax) + { context.Response.StatusCode = 401; + } else + { context.Response.Redirect("/Account/Login"); + } } /// diff --git a/YLErpWeb/Program.cs b/YLErpWeb/Program.cs index 4d7a3f76..a9a0a243 100644 --- a/YLErpWeb/Program.cs +++ b/YLErpWeb/Program.cs @@ -1,3 +1,4 @@ +using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.AspNetCore.StaticFiles; @@ -13,15 +14,17 @@ using System.Text.Encodings.Web; using System.Text.Unicode; using YieldChain.Commons; using YLErp.Abstract; -using YLErp.Modules.SwapModule; +using YLErp.Serialization; +using YLErp.Services.CashRecordModule; using YLErp.Web.App; using YLErp.Web.App.KafkaTask; using YLErp.Web.Hubs; using YLErp.Web.Middleware; +using LogLevel = Microsoft.Extensions.Logging.LogLevel; JsonConvert.DefaultSettings = JsonHelper.GetDefaultSettings; -var logger = NLog.LogManager.Setup().GetCurrentClassLogger(); +var logger = LogManager.Setup().GetCurrentClassLogger(); logger.Debug("init main"); @@ -36,8 +39,8 @@ try { options.JsonSerializerOptions.PropertyNamingPolicy = null; options.JsonSerializerOptions.Converters.Add(new AntiXssConverter()); - options.JsonSerializerOptions.Converters.Add(YLErp.Serialization.CustomDoubleConvert.Default); - options.JsonSerializerOptions.Converters.Add(new YLErp.Serialization.CustomDateTimeConverter()); + options.JsonSerializerOptions.Converters.Add(CustomDoubleConvert.Default); + options.JsonSerializerOptions.Converters.Add(new CustomDateTimeConverter()); }).AddRazorRuntimeCompilation(); //视图渲染绑定中文乱码问题 @@ -49,10 +52,10 @@ try options.MultipartBodyLengthLimit = int.MaxValue; //不限制文件上传大小 }); builder.Services.Configure(builder.Configuration.GetSection("KafkaConfig")); - builder.Services.Configure(builder.Configuration.GetSection("ExternalCashFlow")); + builder.Services.Configure(builder.Configuration.GetSection("ExternalCashFlow")); builder.Services.AddScoped(); builder.Services.AddSingleton(); - builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddResponseCompression(options => { options.Providers.Add(); @@ -67,6 +70,31 @@ try options.AccessDeniedPath = "/Account/Login/"; options.ExpireTimeSpan = TimeSpan.FromSeconds(AuthHelper.ExpireInSeconds); options.SlidingExpiration = true; + options.Events = new CookieAuthenticationEvents + { + OnRedirectToLogin = context => + { + if (context.Request.Headers["X-Requested-With"] == "XMLHttpRequest" || + !context.Request.Headers["Accept"].ToString().Contains("text/html")) + { + context.Response.StatusCode = 401; + return Task.CompletedTask; + } + context.Response.Redirect(context.RedirectUri); + return Task.CompletedTask; + }, + OnRedirectToAccessDenied = context => + { + if (context.Request.Headers["X-Requested-With"] == "XMLHttpRequest" || + !context.Request.Headers["Accept"].ToString().Contains("text/html")) + { + context.Response.StatusCode = 403; + return Task.CompletedTask; + } + context.Response.Redirect(context.RedirectUri); + return Task.CompletedTask; + } + }; }) .AddJwtBearer(AuthHelper.JwtAuthType, options => { @@ -89,7 +117,7 @@ try //NLog: Setup NLog for Dependency injection builder.Logging.ClearProviders(); - builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); + builder.Logging.SetMinimumLevel(LogLevel.Trace); builder.Host.UseNLog(); // Save IServerCollection @@ -101,7 +129,7 @@ try builder.Services.AddHostedService(); builder.Services.AddHostedService(); - builder.Services.AddHostedService(); + builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); @@ -204,5 +232,5 @@ catch (Exception ex) finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) - NLog.LogManager.Shutdown(); + LogManager.Shutdown(); } \ No newline at end of file diff --git a/YLErpWeb/Views/Shared/_MainLayout.cshtml b/YLErpWeb/Views/Shared/_MainLayout.cshtml index c1b22018..849e532b 100644 --- a/YLErpWeb/Views/Shared/_MainLayout.cshtml +++ b/YLErpWeb/Views/Shared/_MainLayout.cshtml @@ -279,6 +279,15 @@ + + diff --git a/YLErpWeb/wwwroot/Scripts/base/main.js b/YLErpWeb/wwwroot/Scripts/base/main.js index a6035990..bd7af171 100644 --- a/YLErpWeb/wwwroot/Scripts/base/main.js +++ b/YLErpWeb/wwwroot/Scripts/base/main.js @@ -2,13 +2,6 @@ var main = window.main || { version: "1.0" }; -// 全局处理AJAX 401未授权响应,自动跳转登录页 -$(document).ajaxError(function (event, jqXHR) { - if (jqXHR.status === 401) { - window.location.href = '/Account/Login'; - } -}); - main.extend = $.extend; //数字格式化 @@ -390,7 +383,6 @@ function __post(url, data, deferred, options) { waitMeFunc(false); }, error(jqXHR, textStatus, errorThrown) { - if (jqXHR.status === 401) return; options && options.suppressError || main.alert('请求失败'); console.error("请求失败,url:" + url + ",status:" + textStatus + ",error:" + errorThrown); }