.NET Core 2项目中已认证用户的HttpContext.User为null问题
我之前在做.NET Core项目时也碰到过几乎一模一样的情况——Identity登录成功、Cookie也正常,但HttpContext.User就是返回null。结合.NET Core 2的身份认证机制,给你几个实用的排查和解决方向:
检查中间件的顺序
.NET Core的中间件执行顺序直接影响身份认证的效果,UseAuthentication()必须放在UseMvc()(或者其他路由中间件)之前,否则请求到达MVC控制器时,身份还没被解析出来。正确的配置应该是这样:public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // 其他中间件(比如UseStaticFiles) app.UseAuthentication(); // 这个一定要在UseMvc前面 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }确认默认认证方案的优先级
你提到同时添加了令牌认证,这很可能是问题所在!如果令牌认证被设置为默认的AuthenticateScheme,那么系统会优先尝试从请求中解析JWT令牌,而不是Cookie。但你的请求只带了Identity的Cookie,所以HttpContext.User就会返回null。
解决方法是明确指定默认认证方案为Identity的Cookie方案,或者在需要获取用户身份时指定Cookie方案:// 方案1:在Startup中设置默认认证方案 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme; options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme; }) .AddJwtBearer(options => { // 你的令牌认证配置 }) .AddCookie(IdentityConstants.ApplicationScheme, options => { // Cookie相关配置(比如过期时间、路径等) }); // 方案2:在代码中手动指定Cookie方案获取身份 var authResult = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme); if (authResult.Succeeded) { var currentUser = authResult.Principal; // 这里就可以正常使用currentUser了 }验证Cookie的安全性设置
如果你在配置Identity Cookie时开启了SecurePolicy = CookieSecurePolicy.Always,但开发环境用的是HTTP而非HTTPS,浏览器会拒绝发送Cookie到服务器,自然就无法解析出用户身份。可以临时改成SameAsRequest来测试:services.ConfigureApplicationCookie(options => { options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; // 其他Cookie配置 });检查登录逻辑的正确性
确保你调用的登录方法是正确的,比如使用SignInManager.PasswordSignInAsync或者SignInManager.SignInAsync,并且返回了成功结果。如果登录过程中出现了未捕获的异常,可能导致身份没有被正确写入Cookie:var signInResult = await _signInManager.PasswordSignInAsync( model.Username, model.Password, model.RememberMe, lockoutOnFailure: false); if (signInResult.Succeeded) { // 登录成功后,身份应该已经被持久化到Cookie中 return RedirectToAction("Index", "Home"); }
内容的提问来源于stack exchange,提问作者RektByMemes

