简体   繁体   English

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

[英]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.我的应用程序中有一个 JWT 令牌实现,并且我实现了 Google 登录。 But now, HttpContext.User claims are not set.但是现在,没有设置HttpContext.User声明。

Here is my startup.cs :这是我的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:这就是我创建 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)
                            );

Normally, it sets HttpContext.User and claims and I can check通常,它设置HttpContext.User和声明,我可以检查

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

but now, this returns null.但现在,这将返回 null。

Do you have any idea why?你知道为什么吗?

I finally got the solution.我终于得到了解决方案。 I just add await _signInManager.SignInAsync(user, false,"JwtBearer");我只是添加await _signInManager.SignInAsync(user, false,"JwtBearer"); and resolved.并解决了。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过使用JWT令牌在Web API上声明角色授权-Asp.net核心标识 - Authorization by a Claim of a Role on Web API using JWT Token- Asp.net Core Identity 使用Microsoft Graph令牌通过Jwt Bearer令牌保护ASP.NET Core Web API - Using Microsoft Graph token to secure ASP.NET Core Web API with Jwt Bearer tokens 如何注销或过期 ASP.NET 内核 Web ZDB974238714CA8DE634A7CE1D08 的 JWT 令牌? - How to logout or expire JWT token for ASP.NET Core Web API? JWT 令牌过期在 Asp.Net Core API 中不起作用? - JWT token expiration not working in Asp.Net Core API? JWT不记名令牌授权不起作用asp net core web api - JWT bearer token Authorization not working asp net core web api ASP.Net Core JWT 登录未设置 HttpContext.User.Claims - ASP.Net Core JWT Login not setting HttpContext.User.Claims 如何使用 jwt 和身份框架注销 asp.net 核心 web API 中的用户 - How to logout user in asp.net core web API with jwt and identity framework 使用ASP.NET Core Web API进行Facebook JWT身份验证 - Facebook JWT authentication using ASP.NET Core Web API 勾选IP和JWT 在ASP.NET核中授权Web Api - Check IP with JWT Authorization in ASP.NET Core Web Api ASP.NET Core 1.0 Web API 中的简单 JWT 身份验证 - Simple JWT authentication in ASP.NET Core 1.0 Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM