LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 6422 min read

API Authentication with JWT

Learn how to secure a Web API using JSON Web Tokens (JWT) for authentication and authorization.

What is JWT?

A JSON Web Token (JWT) is a compact, self-contained token that securely represents a user's identity and claims. The client sends it with each request, and the server verifies it without needing to look anything up in a session store.

Configuring JWT Authentication

Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
};
});
app.UseAuthentication();
app.UseAuthorization();

Issuing a Token

var claims = new[] { new Claim(ClaimTypes.Name, user.Username) };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.UtcNow.AddHours(2),
signingCredentials: credentials);
string tokenString = new JwtSecurityTokenHandler().WriteToken(token);

Protecting Endpoints

Mark a controller or action with `[Authorize]` to require a valid token before the request is allowed through.

[Authorize]
[HttpGet("me")]
public IActionResult GetProfile()
{
string? username = User.Identity?.Name;
return Ok($"Hello, {username}");
}
[Authorize(Roles = "Admin")]
[HttpDelete("{id}")]
public IActionResult DeleteUser(int id) => Ok();
Never Hardcode the Signing Key

The Jwt:Key value must be a long, random secret stored in configuration (or a secrets manager) — never committed to source control. Anyone with this key can forge valid tokens.

FAQs

No — cookie-based authentication and API keys are common alternatives. JWT is especially popular for stateless APIs consumed by mobile apps and SPAs.

Summary

  • JWT is a compact, verifiable token representing a user's identity.
  • [Authorize] protects endpoints, requiring a valid token.
  • [Authorize(Roles = "...")] restricts access further, by role.
Next Lesson →

Configuration & appsettings