ASP.NET Core 8集成OpenID时Cookie Scheme认证失败求助
问题描述
新项目基于ASP.NET Core 8基础模板搭建,使用Fusion Auth作为OpenID认证提供者(后续将接入Keycloak)。配置OpenID认证后,启动应用时日志反复出现Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler: Debug: AuthenticationScheme: Cookies was not authenticated,且用户登录后信息未存储到Cookie中。
项目代码
var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("SampleIdentityDbContextConnection") ?? throw new InvalidOperationException("Connection string 'MagicShareIdentityDbContextConnection' not found."); builder.Services.AddDbContext<MagicShareIdentityDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<MagicShareIdentityDbContext>(); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie(options => { options.LoginPath = "/Account/Login"; }) .AddOpenIdConnect(options => { options.Authority = builder.Configuration["SampleApp:Authority"]; options.ClientId = builder.Configuration["SampleApp:ClientId"]; options.ClientSecret = builder.Configuration["SampleApp:ClientSecret"]; options.ResponseType = "code"; options.SaveTokens = true; options.Scope.Add("openid"); options.Scope.Add("profile"); options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "preferred_username", RoleClaimType = "roles", }; }); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapRazorPages(); IdentityModelEventSource.ShowPII = true; app.Run();
登录日志
dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9] AuthenticationScheme: Cookies was not authenticated. dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9] AuthenticationScheme: Cookies was not authenticated. trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[4] Entering Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler's HandleUnauthorizedAsync. trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[5] Using properties.RedirectUri for 'local redirect' post authentication: '/Identity/Account/ExternalLogin?returnUrl=%2F&handler=Callback'. dbug: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[53] HandleChallenge with Location: https://....B1ZdqdwTVV5cnhEH1EWoYoPj5CH_0AeI=N; expires=Tue, 20 Feb 2024 12:33:53 GMT; path=/signin-oidc; secure; samesite=none; httponly,.AspNetCore.Correlation.Ky-hv-7NZiA_E7ij2KKpHSoFROsN7sfrQSJU5Axp1W4=N; expires=Tue, 20 Feb 2024 12:33:53 GMT; path=/signin-oidc; secure; samesite=none; httponly. info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[12] AuthenticationScheme: OpenIdConnect was challenged. trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[9] Entering Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler's HandleRemoteAuthenticateAsync. trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[24] MessageReceived: '?code=MQgGYb5k9GSCeYKSW75Y4O5-A-mtFsx8pGSGVuuqan8&locale=en&userState=Authenticated'. dbug: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[13] Updating configuration trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[27] Authorization code received. dbug: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[19] Redeeming code for tokens. trce: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[30] Token response received. info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[10] AuthenticationScheme: Identity.External signed in. dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9] AuthenticationScheme: Cookies was not authenticated. dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[8] AuthenticationScheme: Identity.External was successfully authenticated. info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[11] AuthenticationScheme: Identity.External signed out. info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[10] AuthenticationScheme: Identity.Application signed in. info: MagicShare.Areas.Identity.Pages.Account.ExternalLoginModel[0] eagleeye logged in with OpenIdConnect provider. dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9] AuthenticationScheme: Cookies was not authenticated. dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9] AuthenticationScheme: Cookies was not authenticated.
解决方案
问题根源是ASP.NET Core Identity和自定义Cookie认证的冲突:你同时启用了AddDefaultIdentity(自带一套完整的Cookie认证体系,使用Identity.Application等Scheme)和手动添加的AddCookie(使用Cookies Scheme),导致默认认证Scheme混乱,Cookies Scheme从未被实际使用。
修复步骤及修改后的代码:
- 移除手动添加的
AddCookie配置,因为AddDefaultIdentity已经内置了Cookie认证逻辑 - 将全局默认认证Scheme改为Identity的
Identity.Application - 给OpenID Connect配置指定
SignInScheme为IdentityConstants.ApplicationScheme,让登录状态直接存入Identity的Cookie中
var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("SampleIdentityDbContextConnection") ?? throw new InvalidOperationException("Connection string 'MagicShareIdentityDbContextConnection' not found."); builder.Services.AddDbContext<MagicShareIdentityDbContext>(options => options.UseSqlServer(connectionString)); // 保留Identity配置,自动处理Cookie认证 builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<MagicShareIdentityDbContext>(); builder.Services.AddControllersWithViews(); builder.Services.AddAuthentication(options => { // 使用Identity的默认Scheme作为全局默认 options.DefaultScheme = IdentityConstants.ApplicationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddOpenIdConnect(options => { options.Authority = builder.Configuration["SampleApp:Authority"]; options.ClientId = builder.Configuration["SampleApp:ClientId"]; options.ClientSecret = builder.Configuration["SampleApp:ClientSecret"]; options.ResponseType = "code"; options.SaveTokens = true; options.Scope.Add("openid"); options.Scope.Add("profile"); // 指定使用Identity的Cookie存储登录状态 options.SignInScheme = IdentityConstants.ApplicationScheme; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "preferred_username", RoleClaimType = "roles", }; }); var app = builder.Build(); // 中间件配置保持不变 if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapRazorPages(); IdentityModelEventSource.ShowPII = true; app.Run();
补充说明
- 修复后,
AuthenticationScheme: Cookies was not authenticated的日志会消失,因为不再有未被使用的自定义Cookie Scheme - 用户登录后,
Identity.Application会自动创建Cookie存储用户信息,可通过User.Identity.IsAuthenticated验证登录状态 - 后续接入Keycloak时,只需复制当前OpenID Connect配置块,修改
Authority、ClientId、ClientSecret即可,无需改动Cookie相关配置
内容的提问来源于stack exchange,提问作者EagleEye
相关产品推荐
相关产品推荐

