如何在 .net core web API 中更新散列密码?

How to update hashed password in .net core web API?

我将通过 Http Put 操作更新我的散列密码。

这是我的模型:

    [Key, DatabaseGenerated (DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string FullName { get; set; }
    public string UserName { get; set; }

    [NotMapped]
    public string Password { get; set; }

    [Required]
    public byte[] PasswordHash { get; set; }

    [Required]
    public byte[] PasswordSalt { get; set; }

    public byte UserRole { get; set; }

这是我的控制器:

    [HttpPut("{Id}")]
    public async Task<IActionResult> PutUser([FromRoute] int Id, [FromBody] TheUser user)
    {
        if (Id != user.Id)
        {
            return BadRequest();
        }
        CreatePasswordHash(user.Password, out byte[] passwordHash, out byte[] passwordSalt);
        _context.Entry(user).State = EntityState.Modified;
        user.PasswordHash = passwordHash;
        user.PasswordSalt = passwordSalt;
        
        
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (_context.TheUser.Find(Id) == null)
            {
                return NotFound();
            }
            throw;
        }
        catch
        {
            return BadRequest();
        }
        return NoContent();
    }

    private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
    {
        using (var hmac = new System.Security.Cryptography.HMACSHA512())
        {
            passwordSalt = hmac.Key;
            passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
        }
    }

当我 运行 应用程序时,我收到以下错误:

事实上,我要在不知道以前密码的情况下重设用户密码。

但问题是两个变量 passwordHashpasswordSalt 没有得到值。

你创建了这两个属性Required,所以你必须给它们传递值。

您可以轻松删除 Required 属性或将 空字符串 传递给这些属性,然后使用其他操作或方法 更新 它们在插入到您的 db.

之后