与UserManage不同的用户ID

时间:2019-01-22 16:19:04

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

我实现了this lesson,只有一个更改:MySQL => MS SQL。 但是当用户登录时,我看到了不同的UserId,例如:

登录方法中的用户: enter image description here id =“ 2b058ff8-f9d3-4ccf-a5f7-bb528f80a333”

和来自数据库的用户: enter image description here id =“ 7fe​​38d73-e940-4e42-bb15-76a72d2000bd”

登录方法有什么问题? 或者也许用令牌生成方法? 但是,使用注册方法后,我可以找到合适的用户。

登录:

[HttpPost]
    public async Task<object> Login([FromBody] LoginDto model)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

        if (result.Succeeded)
        {
            var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
            var token = await GenerateJwtToken(model.Email, appUser);
            return Json(new GenericResponse<string>(true, "", (string)token));
        }

        throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
    }

注册:

[HttpPost]
    public async Task<object> Register([FromBody] RegisterDto model)
    {
        var user = new AidUser
        {
            UserName = model.Email,
            Email = model.Email,
        };
        var result = await _userManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            //await _userManager.AddToRoleAsync(user, "user");
            await _signInManager.SignInAsync(user, false);
            await _dbContext.SaveChangesAsync();

            var token = await GenerateJwtToken(model.Email, user);

            var profile = new Profile()
            {
                UserId = user.Id,
                Name = model.FirstName,
                LastName = model.LastName,
                CityId = 1
            };

             _dbContext.Profiles.Add(profile);
            await _dbContext.SaveChangesAsync();
            return Json(new GenericResponse<string>(true, "", (string)token));
        }


        throw new ApplicationException("SOMETHINGWENTWRONG");
    }

令牌生成:

private async Task<object> 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)
        };

        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 个答案:

没有答案