Jwt Token

mail@pastecode.io avatar
unknown
csharp
4 years ago
1.3 kB
4
Indexable
Never
[AllowAnonymous]
[HttpPost]
public IActionResult Authenticate([FromBody] EmployeeDto userDto)
{
    var user = _authService.Authenticate(userDto.Username, userDto.Password);

    if (user == null)
    {
        return BadRequest(new { message = "Username or password is incorrect", error = "invalid_grant" });
    }

    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_settings.Secret);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Name, user.Login.ToString())
        }),
        Expires = DateTime.UtcNow.AddDays(7),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);

    return Ok(new
    {
        user.Id,
        Username = user.Login,
        user.FirstName,
        user.LastName,
        Roles = user.Roles.Where(x => x.Value.Active).Select(x => x.Key),
        Token = tokenString,
        tokenDescriptor.Expires
    });
}