【问题标题】:How to update hashed password in .net core web API?如何在 .net 核心 Web API 中更新散列密码?
【发布时间】:2021-09-27 00:19:57
【问题描述】:

我将通过 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 没有得到值。

【问题讨论】:

  • 您实际得到的错误仅与模型验证有关。您已将 PasswordHash 和 PasswordSalt 标记为 [必需]。删除它。您不会将这些字段从视图中发布回来。相反,您在后端填充它们。

标签: c# asp.net-core-webapi asp.net-core-3.1


【解决方案1】:

您创建了这两个属性Required,因此您必须将值传递给它们。

您可以轻松删除 Required 属性或将 空字符串 传递给这些属性,并在插入 db更新它们/strong>。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2015-11-18
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    相关资源
    最近更新 更多