.NET Core 2 login Unauthorized 指定用户名和密码之间的身份验证过程中出了什么问题

.NET Core 2 login Unauthorized specify what was wrong during authentication between Username and Password

我有一个 .NET Core 2 web api 具有登录验证功能。如果凭据无效,我 return 401 未经授权。

代码:

    [AllowAnonymous]
    [HttpPost("authenticate")]
    public IActionResult AuthenticateUser([FromBody] UserResource userResource)
    {
        if (string.IsNullOrWhiteSpace(userResource.UserName))
        {
            ModelState.AddModelError("CheckUserName", "The username can not be empty or whitespace only string");
            return BadRequest(ModelState);
        }

        if (string.IsNullOrWhiteSpace(userResource.Password))
        {
            ModelState.AddModelError("CheckPassword", "The password can not be empty or whitespace only string");
            return BadRequest(ModelState);
        }

        var user = repository.AuthenticateUser(userResource.UserName, userResource.Password);

        if (user == null)
            return Unauthorized();

        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
           {
                new Claim(ClaimTypes.Name, user.Id.ToString())
           }),
            Expires = DateTime.UtcNow.AddMinutes(120),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var tokenString = tokenHandler.WriteToken(token);

        // return basic user info (without password) and token to store client side
        return Ok(new
        {
            Id = user.Id,
            Username = user.UserName,
            FirstName = user.FirstName,
            LastName = user.LastName,
            Token = tokenString
        });
    }  

我想具体说明用户名和密码之间的身份验证过程中出现了什么问题。执行此操作的最佳方法是什么?

谢谢!

最后我决定 return BadRequest 如果用户名不正确,而 Unauthorized 如果用户名正确但密码错误。这个想法是,如果提供了不正确的用户名,最好拒绝该请求,因为该请求无效而不是未经授权。但我不知道这是否是最好的做法。