Advertisement
Advanced Web API

JWT Authentication in ASP.NET Core

Learn how to secure your ASP.NET Core Web API with JSON Web Tokens (JWT). This guide walks through authentication, user registration, token creation, validation, and role-based authorization.

Advertisement

What is JWT?

A JWT is a compact, URL-safe token that carries claims about the authenticated user. It is digitally signed so the server can verify the user identity without storing session state.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwicm9sZXMiOlsiQWRtaW4iXSwiZXhwIjoxNjA4MjM5MDIyfQ
.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

JWTs are ideal for APIs because they are stateless and portable. Unlike server-side sessions, the server does not need to keep a copy of every active token.

  • JWT: Stateless, good for APIs, stored in Authorization header.
  • Cookies: Stateful by default, tied to browser sessions, automatic on web requests.

Setup JWT Authentication

Add authentication services and configure JWT bearer options in Program.cs. You need a signing key, issuer, and audience settings.

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = 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"]))
    };
});

builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Login & Registration

Create endpoints for user registration and login. The login endpoint validates credentials and returns a signed JWT.

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IConfiguration _config;

    public AuthController(IConfiguration config)
    {
        _config = config;
    }

    [HttpPost("register")]
    public IActionResult Register([FromBody] RegisterRequest request)
    {
        // Save user to database, hash password, assign default role.
        return Ok(new { Message = "Registration successful" });
    }

    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginRequest request)
    {
        // Validate credentials here.
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, request.Username),
            new Claim(ClaimTypes.Role, "User")
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Audience"],
            claims: claims,
            expires: DateTime.UtcNow.AddHours(2),
            signingCredentials: creds);

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

Role-Based Access

Use the [Authorize] attribute to protect controllers and restrict access to specific roles.

[Authorize(Roles = "Admin")]
[ApiController]
[Route("api/[controller]")]
public class AdminController : ControllerBase
{
    [HttpGet("dashboard")]
    public IActionResult Dashboard()
    {
        return Ok(new { Message = "Admin dashboard" });
    }
}

Token Validation

ASP.NET Core validates tokens automatically when JWT bearer authentication is enabled. The middleware checks signature, issuer, audience, and expiration before the request reaches the controller.

💡 Tip: Store the JWT secret in a secure location such as Azure Key Vault or environment variables, not in source code.

Security Best Practices

  • Use HTTPS for all requests to prevent token interception.
  • Keep JWT expiration short and refresh tokens securely.
  • Validate user roles and claims on the server side.
  • Invalidate tokens after password changes or logout events when possible.

Summary

JWT provides stateless authentication for APIs through signed tokens.

Register authentication and authorization middleware in Program.cs.

Use login endpoints to issue tokens and protect routes with [Authorize].

Role-based access lets you secure admin-only endpoints and control permissions.

Advertisement
← Previous: Middleware Back to Tutorials →

Related Tutorials

Building RESTful Web APIs

Design and build clean REST APIs using controllers, routes, and JSON responses.

Entity Framework Core Guide

Add a real database to your API with EF Core and migrations.