簡體   English   中英

ASP.NET 核心 Web API:JWT 令牌未設置“HttpContext 用戶”

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

我的應用程序中有一個 JWT 令牌實現,並且我實現了 Google 登錄。 但是現在,沒有設置HttpContext.User聲明。

這是我的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和聲明,我可以檢查

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

但現在,這將返回 null。

你知道為什么嗎?

我終於得到了解決方案。 我只是添加await _signInManager.SignInAsync(user, false,"JwtBearer"); 並解決了。 謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM