ASP.NET Core 8 MVC中Cookie认证LoginPath未按配置重定向问题
以下是导致配置的LoginPath未生效、跳转至默认Identity登录页的常见原因及对应解决方式:
1. Identity服务覆盖了自定义Cookie认证配置
如果项目中引入了Microsoft.AspNetCore.Identity相关依赖,并且调用了AddDefaultIdentity、AddIdentity等方法,这些方法会自动注册一套默认的Cookie认证方案(名称为Identity.Application),并将其设为默认认证方案,直接覆盖你通过AddCookie配置的自定义方案。此时未授权请求会默认走Identity的登录路径/Identity/Account/Login。
若不需要Identity的默认认证体系,可移除相关AddIdentity系列调用;若需保留,需显式指定使用自定义的Cookie认证方案。
2. 未显式设置默认认证/挑战方案
虽然你在AddAuthentication中传入了CookieAuthenticationDefaults.AuthenticationScheme,但需确保显式设置默认的认证和挑战方案,避免被其他逻辑覆盖:
builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(opts => { opts.LoginPath = "/Home/Login"; opts.Cookie.Name = "MyAppAuthCookie"; // 不要设置为空 opts.ExpireTimeSpan = TimeSpan.FromMinutes(30); opts.AccessDeniedPath = "/Home/Unauthorized"; });
3. Cookie名称设为空的合规问题
将opts.Cookie.Name设为空字符串不符合HTTP Cookie规范,浏览器可能无法正常存储或识别该Cookie,导致认证流程异常,触发默认跳转逻辑。务必给Cookie设置一个合法的名称,比如"MyAppAuthCookie"。
4. 中间件顺序错误
认证中间件的加载顺序直接影响逻辑生效,必须确保UseAuthentication()在UseAuthorization()之前,且位于UseRouting()之后、UseEndpoints()之前:
app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
5. [Authorize]属性指定了其他认证方案
如果控制器或Action上的[Authorize]属性指定了非自定义Cookie的认证方案,会忽略你配置的默认规则。确保属性未指定额外Scheme,或显式绑定你的Cookie方案:
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] public class AdminController : Controller { // 控制器逻辑 }
内容的提问来源于stack exchange,提问作者DonDavid12

