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

ASP.NET Core 8.0自定义Cookie认证配置不生效问题求助

ASP.NET Core 8.0 自定义Cookie认证配置不生效问题解决方案

你的问题核心在于ASP.NET Core Identity的默认Cookie认证方案覆盖了自定义配置。AddIdentity方法内部会自动注册并配置一套默认的Cookie认证方案(标识为IdentityConstants.ApplicationScheme,对应Cookie名称.AspNetCore.Identity.Application),而你手动添加的自定义Cookie方案并未被Identity的SignInManager、授权中间件等组件使用,导致修改的LoginPath、Cookie名称等配置不生效。

正确配置步骤

  1. 移除多余的自定义AddCookie注册
    不需要手动调用AddCookie("cookie"),因为AddIdentity已经自动完成了Cookie认证服务的注册。

  2. 在AddIdentity之后配置Application Cookie
    使用ConfigureApplicationCookie直接修改Identity自带的Cookie配置,这是官方推荐的修改Identity Cookie行为的方式。

  3. 明确指定默认认证方案
    确保默认认证、挑战、登录方案指向Identity的Application Scheme,避免中间件使用错误的方案。

完整代码示例

// 1. 先注册Identity服务(AddIdentity会自动注册默认Cookie认证)
builder.Services.AddIdentity<User, IdentityRole>(options =>
{
    options.SignIn.RequireConfirmedAccount = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();

// 2. 配置Identity的Application Cookie,覆盖默认设置
builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = "Cookie";
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromHours(5);
    options.Cookie.MaxAge = options.ExpireTimeSpan;
    options.LogoutPath = new PathString("/LogOut");
    options.LoginPath = new PathString("/Login");
    options.AccessDeniedPath = new PathString("/AccessDenied");
    options.SlidingExpiration = true;
});

// 3. 设置默认认证方案为Identity的Application Scheme
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ApplicationScheme;
});

// 确保中间件顺序正确(Program.cs中)
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

// 必须先启用认证,再启用授权
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

关键说明

  • AddIdentity内部已经注册了UserManager、SignInManager、UserStore等服务,无需手动重复注册,除非你有自定义实现。
  • ConfigureApplicationCookie是专门用来配置Identity默认Cookie的扩展方法,它会直接修改IdentityConstants.ApplicationScheme对应的选项,确保Identity组件使用你的自定义配置。
  • 测试前请清除浏览器中残留的.AspNetCore.Identity.ApplicationCookie,避免旧Cookie干扰结果。

内容的提问来源于stack exchange,提问作者motaz allala

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:52:40