Search code examples
c#.netasp.net-corejwt

Password Updates Automatically


Asp.Net Web API with .net core is updating the password automatically on JWT token generation.

So firstly, I had an MVC5 application with asp net membership tables, and wanted to create an API for the same with .net core.

And to support both MVC5 Web APP and WEB API. I added four more columns for AspNetUsers table (ConcurrencyStamp, LockoutEnd, NormalizedEmail, NormalizedUserName).

Although I'm able to get JWT token without any issues, it's also updating the password each time I generate the JWT token which is not allowing users to login from MV5 web APP.

Below is the JWT generate token code:

[Route("login")] // /login
[HttpPost]
public async Task<ActionResult> Login([FromBody] LoginViewModel 
 model)
{
    try
    {
        var user = await 
        _userManager.FindByNameAsync(model.Username);
        if (user != null && await 
        _userManager.CheckPasswordAsync(user, model.Password))
        {
            
            var claim = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id)
            };

            var signinKey = new SymmetricSecurityKey(
              
            Encoding.UTF8.GetBytes(_configuration["Jwt:SigningKey"]));

            int expiryInMinutes = 
            Convert.ToInt32(_configuration["Jwt:ExpiryInMinutes"]);

            var token = new JwtSecurityToken(
              issuer: _configuration["Jwt:Site"],
              claims: claim,
              audience: _configuration["Jwt:Site"],
              expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),
              signingCredentials: new SigningCredentials(signinKey, 
                     SecurityAlgorithms.HmacSha256)
            );

            return Ok(
              new
              {
                  token = new 
                  JwtSecurityTokenHandler().WriteToken(token),
                  expiration = token.ValidTo,
                  userName = user.UserName
              });
        }
        return Unauthorized();

    }
    catch (Exception ex)
    {
        return Unauthorized();
    }
}

Please let me know how to stop updating the PasswordHash and SecurityStamp column in AspNetUsers on generating JWT token.

Update: CheckPasswordAsync (used in web API) method is updating the password field and PasswordSignInAsync method is used in web app.


Solution

  • @KirkLarin, thanks a lot and it helped me to solve the problem by adding the below code in StartUp.cs file under Configure service method

    public void ConfigureServices(IServiceCollection services)
    {
              services.Configure<PasswordHasherOptions>(options => options.CompatibilityMode = 
                PasswordHasherCompatibilityMode.IdentityV2);
    }