Generate JWT login API

mail@pastecode.io avatar
unknown
csharp
2 years ago
1.7 kB
5
Indexable
Never
[AllowAnonymous]
[HttpPost("login")]
public async Task<IActionResult> Login(LoginModel model)
{
    IdentityUser user = await userManager.FindByEmailAsync(model.Email);

    if (user is not null)
    {
        if (await userManager.CheckPasswordAsync(user, model.Password))
        {
            List<string> userRoles = (List<string>)await userManager.GetRolesAsync(user);

            List<Claim> authClaims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            foreach (string userRole in userRoles)
            {
                authClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }

            SymmetricSecurityKey authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"]));
            JwtSecurityToken token = new JwtSecurityToken(
                claims: authClaims,
                issuer: configuration["JWT:ValidIssuer"],
                audience: configuration["JWT:ValidAudience"],
                signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256),
                expires: model.RememberMe ? DateTime.Now.AddDays(365) : DateTime.Now.AddDays(1)
                );

            return Ok(new JwtSecurityTokenHandler().WriteToken(token));
        }
        else
        {
            return Unauthorized("Adgangskoden var forkert.");
        }
    }

    return Unauthorized("Emailen findes ikke i systemet.");
}