In this post, we will explore how to generate JSON Web Tokens (JWT) in an ASP.NET Core application using the Microsoft.AspNetCore.Identity
library. JWTs are commonly used for securing APIs by ensuring that the client making the request is authenticated.
Setting Up the Environment
First, ensure you have the necessary NuGet packages installed in your ASP.NET Core project:
Microsoft.AspNetCore.Identity
Microsoft.AspNetCore.Mvc
Microsoft.IdentityModel.Tokens
System.IdentityModel.Tokens.Jwt
Creating the AuthController
Below is a sample implementation of an AuthController
that handles user login and JWT generation.
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace RedMango_API.Controllers
{
[Route("api/auth")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly string _secretKey;
public AuthController(UserManager<ApplicationUser> userManager, IConfiguration configuration)
{
_userManager = userManager;
_secretKey = configuration.GetValue<string>("ApiSettings:Secret");
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequestDTO model)
{
var user = await _userManager.FindByNameAsync(model.UserName);
if (user == null || !await _userManager.CheckPasswordAsync(user, model.Password))
{
return Unauthorized("Username or password is incorrect");
}
var token = GenerateJwtToken(user);
return Ok(new { token });
}
private string GenerateJwtToken(ApplicationUser user)
{
var roles = _userManager.GetRolesAsync(user).Result;
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Role, roles.FirstOrDefault() ?? string.Empty)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "yourdomain.com",
audience: "yourdomain.com",
claims: claims,
expires: DateTime.Now.AddDays(7),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
Explanation
Dependencies: The necessary namespaces are imported to handle identity, JWT, and claims.
Controller Setup: The
AuthController
is decorated with[ApiController]
and[Route("api/auth")]
attributes to define it as an API controller and set the route.Constructor: The constructor initializes the
UserManager
and retrieves the secret key from the configuration.Login Endpoint: The
Login
method accepts aLoginRequestDTO
object, checks the user's credentials, and returns a JWT if the credentials are valid.GenerateJwtToken Method: This method creates the JWT by:
Retrieving the user's roles.
Creating claims for the token.
Generating a symmetric security key and signing credentials.
Creating and returning the JWT.
Conclusion
This example demonstrates how to implement JWT authentication in an ASP.NET Core application. By following these steps, you can secure your APIs and ensure that only authenticated users can access them.