【问题标题】:How do I get the user info for whom the jwt token was issued?如何获取为其颁发 jwt 令牌的用户信息?
【发布时间】:2020-07-17 08:15:17
【问题描述】:

我在我的 asp.net 核心应用程序中创建了一个基于令牌的身份验证。当我使用正确的登录模型发布时,它给了我令牌。现在我想知道如何获取为其生成此令牌的用户的信息。 这是创建令牌的代码。如果我能提供任何其他信息,请告诉我。

if (ModelState.IsValid)
{
    var user = await _userManager.FindByNameAsync(model.UserName);
    if (user != null)
    {
         var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
         if (result.Succeeded)
         {
            var claims = new List<Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub,user.Email),
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName,user.UserName)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:key"]));
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                                _config["Tokens:Issuer"],
                                _config["Tokens:Audience"],
                                claims,
                                expires: DateTime.UtcNow.AddMinutes(20),
                                signingCredentials: cred );    
            var results = new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                                expiration = token.ValidTo
            };
            return Created("", results);
        }
    }
}
return BadRequest();

【问题讨论】:

    标签: asp.net asp.net-core jwt


    【解决方案1】:

    经过一番搜索,我找到了解决方案。您可以从令牌中获取用户信息

    [HttpGet]
            public IActionResult GetUser([FromHeader]string token)
            {
    
                var stream = token;
                var handler = new JwtSecurityTokenHandler();
                var jsonToken = handler.ReadToken(stream);
                var tokenS = handler.ReadToken(stream) as JwtSecurityToken;
                var jti = tokenS.Claims.First(claim => claim.Type == "sub").Value;
                return Created("", jti);
            }
    

    【讨论】:

    • 这是不是获取用户令牌的正确方法。您必须从 HEADER 读取令牌
    • @FarhadZamani 你能举个例子或详细解释一下吗?
    【解决方案2】:

    可以像这样通过ClaimsIdentity获取用户信息

    var userIdentity = (User.Identity as ClaimsIdentity);
    
    string userName = userIdentity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;
    string email = userIdentity.FindFirst(JwtRegisteredClaimNames.Sub).Value;
    string guid = userIdentity.FindFirst(JwtRegisteredClaimNames.Jti).Value;
    

    然后将var claims = new [] 更改为var claims = new List&lt;Claim&gt;()

    register IHttpContextAccessor in DI 并从Constructor 获取它以访问HttpContext.User

    var claimsIdentity = _contextAccessor.HttpContext.User.Identity as ClaimsIdentity;
    var userName = claimsIdentity?.FindFirst(JwtRegisteredClaimNames.UniqueName);
    

    这个link 可能对你有帮助

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 2016-08-07
      • 2022-06-13
      • 1970-01-01
      • 2019-04-18
      • 2021-10-22
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      相关资源
      最近更新 更多