验证后,ASP.net核心api上的User.identity.name为null

时间:2017-11-21 21:50:53

标签: asp.net-web-api asp.net-core-mvc

我是asp.net的新手,我正在尝试做一个简单的休息api。 我需要获取当前登录用户的用户名。  我User.Identity.IsAuthenticated为真,但User.Identity.Name为空。我正在使用jwt令牌进行身份验证。

这是我的登录方法

        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginData jsonUser) {
            IdentityUser claimedUser;
            try {
                claimedUser = _userManager.Users.First(
                    user => user.Email == jsonUser.username || user.UserName == jsonUser.username);
            } catch (Exception e) {
                return NotFound("No user with this username : " + e);
            }


            bool isPasswordCorrect = await _userManager.CheckPasswordAsync(claimedUser, jsonUser.Password);
            return isPasswordCorrect
                ? Ok(GenerateJwtToken(claimedUser.Email, claimedUser))
                : StatusCode(401, "bad login or password");
        }


        //Génération du token JWT
        private string GenerateJwtToken(string email, IdentityUser user) {
            var claims = new List<Claim> {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                new Claim(JwtRegisteredClaimNames.GivenName, user.UserName)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"]));

            var token = new JwtSecurityToken(
                _configuration["JwtIssuer"],
                _configuration["JwtIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

如何获取当前用户名?

0 个答案:

没有答案