Understanding JWT Authentication in .NET

What is JWT Authentication?

JWT (JSON Web Token) is a compact and self-contained way to securely transmit information between parties as a JSON object. It is widely used for authentication and authorization in APIs.

  • Compact: Tokens are small and can be easily transmitted via URLs, headers, or cookies.
  • Self-Contained: Contains all the necessary information to validate the token.
  • Secure: Tokens are signed using algorithms like HMAC SHA256 or RSA.

Why Use JWT Authentication in .NET?

JWT is ideal for stateless authentication in APIs. It eliminates the need to store session data on the server, making it a preferred choice for scalable applications.


How to Implement JWT Authentication in .NET

Follow these steps to add JWT authentication to your .NET application:

1. Install Required Packages


// Install NuGet packages
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Install-Package System.IdentityModel.Tokens.Jwt

                

These packages provide tools for working with JWT in .NET.

2. Configure Authentication in Program.cs


// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "https://yourdomain.com",
            ValidAudience = "https://yourdomain.com",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKeyHere"))
        };
    });

builder.Services.AddControllers();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

                

The UseAuthentication middleware validates the JWT token in incoming requests.

3. Create a Token Generation Endpoint


// Controllers/AuthController.cs
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel login)
    {
        if (login.Username == "user" && login.Password == "password")
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, login.Username),
                new Claim(ClaimTypes.Role, "User")
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKeyHere"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: "https://yourdomain.com",
                audience: "https://yourdomain.com",
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
        }
        return Unauthorized();
    }
}

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

                

The Login action generates a JWT token for valid users.

4. Protect an API Endpoint


// Controllers/ValuesController.cs
[ApiController]
[Route("api/values")]
public class ValuesController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public IActionResult GetValues()
    {
        return Ok(new[] { "Value1", "Value2" });
    }
}

                

The [Authorize] attribute ensures that only authenticated requests can access the endpoint.

5. Test Your API


// Step 1: POST /api/auth/login
// Body: { "username": "user", "password": "password" }
// Response: { "token": "" }

// Step 2: GET /api/values
// Header: Authorization: Bearer 

                

Use tools like Postman to test the authentication flow.