You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7.0 Cookie认证登录路径异常:配置/User/Login却跳转/Account/Login

问题原因分析

你遇到的问题是因为ASP.NET Core Identity的AddIdentity方法会自动配置Cookie认证,并且其内部配置会覆盖你手动调用AddCookie的设置。

AddIdentity默认使用IdentityConstants.ApplicationScheme作为认证方案,而你手动配置的是CookieAuthenticationDefaults.AuthenticationScheme,二者属于不同的认证方案。当[Authorize]属性生效时,会优先使用Identity默认的Cookie配置,所以你的LoginPath设置没有生效,仍然跳转默认的/Account/Login。

解决方案

推荐通过AddIdentity的ConfigureApplicationCookie方法直接配置Identity的Cookie参数,替代单独的AddCookie配置,具体修改如下:

1. 修改Program.cs中的Identity配置

删除你手动添加的AddAuthentication和AddCookie代码段,改为在AddIdentity后添加ConfigureApplicationCookie配置:

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString(SystemConstants.MainConnectionString);
builder.Services.AddDbContext<WebShopDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddHttpClient();

// Add services to the container.
builder.Services.AddControllersWithViews()
                .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<LoginRequestValidator>());

// 修改Identity配置,添加Cookie路径设置
builder.Services.AddIdentity<AppUser, AppRole>()
    .AddEntityFrameworkStores<WebShopDbContext>()
    .AddDefaultTokenProviders()
    .ConfigureApplicationCookie(options =>
    {
        options.LoginPath = "/User/Login";
        options.AccessDeniedPath = "/User/AccessDenied";
    });

builder.Services.AddTransient<IUserApiClient, UserApiClient>();

//add runtime
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
}
else
{
    builder.Services.AddControllersWithViews();
}

var app = builder.Build();

// ... 后续中间件配置保持不变

2. 统一SignIn使用的认证方案

在UserController的Login方法中,将SignIn的认证方案改为Identity默认的IdentityConstants.ApplicationScheme(和上面的配置对应):

await HttpContext.SignInAsync(
            IdentityConstants.ApplicationScheme, // 修改为Identity默认认证方案
            userPrincipal,
            authProperties);
验证修改

完成上述修改后,重新启动应用,未登录状态下访问Home/Index时,应该会正确跳转到/User/Login路径。

内容的提问来源于stack exchange,提问作者Chung Truong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:17:34