Search code examples
authentication.net-coremessageasp.net-core-webapiunauthorized

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


I have a .NET Core 2 web api with a function for login authentication. If the credentials are not valid i return 401 Unauthorized.

Code:

    [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
        });
    }  

I would like to be specific about what was wrong during authentication between Username and Password. What is the best way to do this?

Thanks!


Solution

  • In the end i decided to return BadRequest in case of incorrect username, and Unauthorized in case of correct username but wrong password. The idea is that if an incorrect user name is provided, it is probably best to reject the request as invalid rather than unauthorized. But i do not know if this is the best practice to follow.