What is JWT and how do you implement JWT authentication?

4 minintermediateASP.NET-CoreJWTauthenticationsecurity

Quick Answer

A JWT (JSON Web Token) is a compact, URL-safe, digitally signed token with three parts — Header, Payload (claims), and Signature — used for stateless authentication. The server issues a signed token on login; the client sends it in the `Authorization: Bearer` header, and the API validates the signature/claims via JWT bearer authentication (`AddJwtBearer`) without server-side session state.

Detailed Answer

JWT (JSON Web Token) is a compact, URL-safe token format for securely transmitting information between parties as a JSON object. It consists of three parts: Header, Payload, and Signature.

JWT Structure:

xxxxx.yyyyy.zzzzz
Header.Payload.Signature

Implementation:

Step 1: Create JWT Token Generation Service

public class JwtTokenService
{
    private readonly IConfiguration _configuration;

    public JwtTokenService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public string GenerateToken(string userId, string email, List roles)
    {
        var securityKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var claims = new List
        {
            new Claim(JwtRegisteredClaimNames.Sub, userId),
            new Claim(JwtRegisteredClaimNames.Email, email),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

        var token = new JwtSecurityToken(
            issuer: _configuration["Jwt:Issuer"],
            audience: _configuration["Jwt:Audience"],
            claims: claims,
            expires: DateTime.Now.AddHours(1),
            signingCredentials: credentials
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

Step 2: Login Endpoint

[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
    // Validate credentials (simplified)
    if (ValidateUser(model.Username, model.Password))
    {
        var token = _jwtTokenService.GenerateToken(
            userId: "123",
            email: model.Username,
            roles: new List { "User", "Admin" }
        );

        return Ok(new { token });
    }

    return Unauthorized();
}

Step 3: appsettings.json Configuration

{
  "Jwt": {
    "Key": "YourSuperSecretKeyThatIsAtLeast32CharactersLong",
    "Issuer": "YourApp",
    "Audience": "YourAppUsers"
  }
}