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

ASP.NET Core Web API中JWT令牌无法正确设置HttpContext.User的问题求助

ASP.NET Core Web API中JWT令牌无法正确设置HttpContext.User的问题求助

各位大佬好,我最近在应用里同时实现了JWT令牌认证和Google登录功能,但遇到了一个头疼的问题——HttpContext.User里的Claims始终无法正确设置,导致我执行var userEmail = HttpContext.User.FindFirst(ClaimTypes.Email).Value时返回null。

之前只配置JWT的时候一切正常,Claims都能正常读取,加了Google登录之后就出问题了,下面是我的相关代码,麻烦大家帮我排查下问题所在:

Startup.cs 中的认证配置

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddGoogle(options =>
{
    options.ClientId = CLIENT_ID;
    options.ClientSecret = SECRET;
    options.SaveTokens = true;
})
.AddJwtBearer(options =>
{
    options.SaveToken = true;
    options.RequireHttpsMetadata = false;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = Configuration["JWT:ValidAudience"],
        ValidIssuer = Configuration["JWT:ValidIssuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
    };
    options.Events = new JwtBearerEvents
    {
        OnMessageReceived = context =>
        {
            context.Token = context.Request.Cookies[CookieAuthenticationDefaults.AuthenticationScheme];
            context.HttpContext.User = context.Principal;
            return Task.CompletedTask;
        },
    };
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);

密码登录的代码

Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(Email, Password, false, true);

JWT令牌生成代码

var authClaims = new List<Claim>
{
    new Claim(ClaimTypes.Email, user.UserName),
    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    new Claim(ClaimTypes.Name, user.FirstName)
};

var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(["JWT:Secret"]));

var token = new JwtSecurityToken(
    issuer: ["JWT:ValidIssuer"],
    audience: ["JWT:ValidAudience"],
    expires: DateTime.UtcNow.AddHours(1),
    claims: authClaims,
    signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);

有没有大佬能帮我分析下,为什么现在HttpContext.User的Claims无法正常设置了?

备注:内容来源于stack exchange,提问作者barba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 15:27:35