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.
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.
Follow these steps to add JWT authentication to your .NET application:
// 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.
// 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.
// 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.
// 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.
// 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.