简体   繁体   中英

ASP.NET Core Web API: JWT token does not set "HttpContext User"

I have a JWT token implementation in my app and I implemented Google login. But now, HttpContext.User claims are not set.

Here is my 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);

And I log in like this:

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

This is how I create the JWT token:

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)
                            );

Normally, it sets HttpContext.User and claims and I can check

var userEmail = HttpContext.User.FindFirst(ClaimTypes.Email).Value

but now, this returns null.

Do you have any idea why?

I finally got the solution. I just add await _signInManager.SignInAsync(user, false,"JwtBearer"); and resolved. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM