fix(auth): 解决AJAX请求401未授权处理问题
- 将全局AJAX 401处理逻辑从main.js移至_MainLayout.cshtml - 移除main.js中的重复401状态检查代码 - 在Cookie认证配置中添加自定义重定向事件处理 - 优化中间件中AJAX请求检测逻辑,支持多种请求类型判断 - 更新依赖注入和服务注册中的命名空间引用 - 添加日志管理器相关引用和配置优化
This commit is contained in:
@@ -29,16 +29,22 @@ namespace YLErp.Web.Middleware
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 统一拒绝请求:清除Cookie并跳转登录页或返回401
|
||||
/// 统一拒绝请求:清除Cookie并返回401或跳转登录页
|
||||
/// </summary>
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+37
-9
@@ -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<KafkaConfig>(builder.Configuration.GetSection("KafkaConfig"));
|
||||
builder.Services.Configure<YLErp.Services.CashRecordModule.ExternalCashFlowOptions>(builder.Configuration.GetSection("ExternalCashFlow"));
|
||||
builder.Services.Configure<ExternalCashFlowOptions>(builder.Configuration.GetSection("ExternalCashFlow"));
|
||||
builder.Services.AddScoped<IViewRenderService, ViewRenderService>();
|
||||
builder.Services.AddSingleton<IKafkaProduce, KafkaProduceHelper>();
|
||||
builder.Services.AddTransient<YLErp.Services.CashRecordModule.IExternalCashFlowService, YLErp.Services.CashRecordModule.ExternalCashFlowService>();
|
||||
builder.Services.AddTransient<IExternalCashFlowService, ExternalCashFlowService>();
|
||||
builder.Services.AddResponseCompression(options =>
|
||||
{
|
||||
options.Providers.Add<BrotliCompressionProvider>();
|
||||
@@ -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<ClientBalanceTask>();
|
||||
|
||||
builder.Services.AddHostedService<ClientReskCheckKafkaTask>();
|
||||
builder.Services.AddHostedService<YLErp.Web.App.HostedTaskService>();
|
||||
builder.Services.AddHostedService<HostedTaskService>();
|
||||
builder.Services.AddHostedService<ClientBalanceMonitorTotalKafkaTask>();
|
||||
builder.Services.AddHostedService<ClientBalanceMonitorSingleKafkaTask>();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -279,6 +279,15 @@
|
||||
<script src="~/statics/bundles/vue.js?v=@(HtmlUtil.JsVersion)"></script>
|
||||
<script src="~/Scripts/app/mainLayout.js?v=@(HtmlUtil.JsVersion)"></script>
|
||||
<script src="~/Scripts/utils.js?v=@(HtmlUtil.JsVersion)"></script>
|
||||
|
||||
<script>
|
||||
// 全局处理AJAX 401未授权响应,自动跳转登录页
|
||||
$(document).ajaxError(function (event, jqXHR) {
|
||||
if (jqXHR.status === 401) {
|
||||
window.location.href = '/Account/Login';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<script src="/Front/otcformat?v=@(HtmlUtil.JsVersion)"></script>
|
||||
<script src="~/statics/bundles/qiankun-v2.10.5/index.umd.min.js"></script>
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user