Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // *** Request model for changing password ***
- public class ChangePasswordRequest
- {
- public string Username { get; set; }
- public string OldPassword { get; set; }
- public string NewPassword { get; set; }
- }
- // *** New user repository handler for changing password ***
- public void ChangePassword(ChangePasswordRequest request)
- {
- var isAuthenticated = Authenticate(request.Username, request.OldPassword);
- if (!isAuthenticated)
- throw new InvalidOperationException("Authentication failed");
- // Salt and hash pwd
- byte[] salt = RandomNumberGenerator.GetBytes(128 / 8); // divide by 8 to convert bits to bytes
- string b64Salt = Convert.ToBase64String(salt);
- byte[] hash =
- KeyDerivation.Pbkdf2(
- password: request.NewPassword,
- salt: salt,
- prf: KeyDerivationPrf.HMACSHA256,
- iterationCount: 100000,
- numBytesRequested: 256 / 8);
- string b64Hash = Convert.ToBase64String(hash);
- // Update user
- var target = _users.Single(x => x.Username == request.Username);
- target.PwdSalt = b64Salt;
- target.PwdHash = b64Hash;
- }
- // *** New change password action for user controller ***
- [HttpPost("[action]")]
- public ActionResult ChangePassword([FromBody] ChangePasswordRequest request)
- {
- try
- {
- _userRepository.ChangePassword(request);
- return Ok();
- }
- catch (InvalidOperationException ex)
- {
- return BadRequest(ex.Message);
- }
- }
Add Comment
Please, Sign In to add comment