otkalce

Authentication - change password

Mar 10th, 2023
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | Source Code | 0 0
  1. // *** Request model for changing password ***
  2.     public class ChangePasswordRequest
  3.     {
  4.         public string Username { get; set; }
  5.         public string OldPassword { get; set; }
  6.         public string NewPassword { get; set; }
  7.     }
  8.  
  9. // *** New user repository handler for changing password ***
  10.         public void ChangePassword(ChangePasswordRequest request)
  11.         {
  12.             var isAuthenticated = Authenticate(request.Username, request.OldPassword);
  13.  
  14.             if (!isAuthenticated)
  15.                 throw new InvalidOperationException("Authentication failed");
  16.  
  17.             // Salt and hash pwd
  18.             byte[] salt = RandomNumberGenerator.GetBytes(128 / 8); // divide by 8 to convert bits to bytes
  19.             string b64Salt = Convert.ToBase64String(salt);
  20.  
  21.             byte[] hash =
  22.                 KeyDerivation.Pbkdf2(
  23.                     password: request.NewPassword,
  24.                     salt: salt,
  25.                     prf: KeyDerivationPrf.HMACSHA256,
  26.                     iterationCount: 100000,
  27.                     numBytesRequested: 256 / 8);
  28.             string b64Hash = Convert.ToBase64String(hash);
  29.  
  30.             // Update user
  31.             var target = _users.Single(x => x.Username == request.Username);
  32.             target.PwdSalt = b64Salt;
  33.             target.PwdHash = b64Hash;
  34.         }
  35.  
  36. // *** New change password action for user controller ***
  37.         [HttpPost("[action]")]
  38.         public ActionResult ChangePassword([FromBody] ChangePasswordRequest request)
  39.         {
  40.             try
  41.             {
  42.                 _userRepository.ChangePassword(request);
  43.                 return Ok();
  44.             }
  45.             catch (InvalidOperationException ex)
  46.             {
  47.                 return BadRequest(ex.Message);
  48.             }
  49.         }
Tags: jwt-token
Add Comment
Please, Sign In to add comment