LESSON 14 OF 18

14. JWT Authentication and Authorization

Learn how to implement user registration and login, validate JWT access tokens, and apply role- and policy-based authorization in an ASP.NET Core Web API.

50 dk 78

Introduction

So far, we have designed resources, standardized errors, added pagination, and documented the API. In a real application, however, we cannot allow every client to access every resource. We need two separate capabilities: authentication, which verifies who the caller is, and authorization, which determines what that authenticated caller is allowed to do.

In this lesson, we will build a practical JWT flow for an ASP.NET Core Web API. A user will register, sign in, receive an access token, and send that token in the Authorization: Bearer header. ASP.NET Core will validate the token and expose the user identity through HttpContext.User. We will then protect endpoints with role- and policy-based rules.

A JWT is not a replacement for a password. It is a signed access token. Passwords must never be stored as plain text.

Authentication versus authorization

Authentication

Authentication identifies the caller. During a username-and-password login, the application verifies the password. If verification succeeds, it creates an identity and represents that identity through claims that can be placed in a token.

Authorization

Authorization determines which resources or operations the authenticated user may access. For example, every signed-in user might read their own profile, while only an Admin user may delete products. This distinction matters: registering the authentication middleware does not automatically protect endpoints. You must apply [Authorize], a role, or a policy to the endpoint.

User model and DTOs

First, define the persistence model and request/response contracts. Sensitive entity properties such as the password hash must not be exposed through response DTOs.

public sealed class User {    public Guid Id { get; set; }    public string Email { get; set; } = null!;    public string PasswordHash { get; set; } = null!;    public string Role { get; set; } = "User";    public bool IsActive { get; set; } = true; } public sealed record RegisterRequest(    string Email,    string Password); public sealed record LoginRequest(    string Email,    string Password); public sealed record LoginResponse(    string AccessToken,    DateTime ExpiresAtUtc);

In a production application, create a unique database index for email addresses. Define case-sensitivity consistently in both the database and application layers. Normalizing email addresses during registration helps prevent multiple accounts created with different casing.

Storing passwords safely

Using a general-purpose hash such as SHA-256 as a password storage mechanism is not the right approach. Password hashing requires a dedicated, deliberately slow algorithm with salt and appropriate verification behavior. If you use ASP.NET Core Identity, PasswordHasher<TUser> is a ready-made option.

using Microsoft.AspNetCore.Identity; public sealed class PasswordService {    private readonly PasswordHasher<User> _hasher = new();    public string Hash(User user, string password) =>        _hasher.HashPassword(user, password);    public bool Verify(User user, string password, string hash) =>        _hasher.VerifyHashedPassword(user, hash, password)        == PasswordVerificationResult.Success; }

For production systems that need account lockout, password reset, email confirmation, multi-factor authentication, refresh-token management, and other identity lifecycle features, ASP.NET Core Identity or an external OpenID Connect provider is usually the safer choice. The service in this lesson is intentionally simplified so the JWT mechanics remain clear.

Configuring JWT settings

Never place the signing key in source code. Use user-secrets during development and a secret manager or protected environment configuration in production.

public sealed class JwtOptions {    public string Issuer { get; set; } = null!;    public string Audience { get; set; } = null!;    public string SigningKey { get; set; } = null!;    public int AccessTokenMinutes { get; set; } = 15; }{  "Jwt": {    "Issuer": "ProfessionalRestApi",    "Audience": "ProfessionalRestApi.Client",    "SigningKey": "development-only-long-secret-key-change-me",    "AccessTokenMinutes": 15  } }

The signing key must be long and unpredictable. If it is exposed, an attacker may create tokens that appear valid. Key rotation, short access-token lifetimes, and—when required—a separate refresh-token design should be planned for production.

Creating the token service

After a successful login, we can add the user ID, email, and role as claims. The role claim created in the token must match the role claim type expected by JWT validation.

using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; public sealed class JwtTokenService(IOptions<JwtOptions> options) {    private readonly JwtOptions _options = options.Value;    public LoginResponse CreateToken(User user)    {        var expiresAt = DateTime.UtcNow.AddMinutes(_options.AccessTokenMinutes);        var claims = new[]        {            new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),            new Claim(JwtRegisteredClaimNames.Email, user.Email),            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),            new Claim(ClaimTypes.Email, user.Email),            new Claim(ClaimTypes.Role, user.Role)        };        var key = new SymmetricSecurityKey(            Encoding.UTF8.GetBytes(_options.SigningKey));        var credentials = new SigningCredentials(            key, SecurityAlgorithms.HmacSha256);        var token = new JwtSecurityToken(            issuer: _options.Issuer,            audience: _options.Audience,            claims: claims,            expires: expiresAt,            signingCredentials: credentials);        return new LoginResponse(            new JwtSecurityTokenHandler().WriteToken(token),            expiresAt);    } }

Do not place passwords, password hashes, secrets, or other sensitive information in a token. Claims can be read by the client; the signature protects integrity but does not encrypt the JWT payload.

Registering the authentication middleware

Add the Microsoft.AspNetCore.Authentication.JwtBearer package, then configure the services and middleware order.

using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Security.Claims; using System.Text; var builder = WebApplication.CreateBuilder(args); builder.Services.Configure<JwtOptions>(    builder.Configuration.GetSection("Jwt")); var jwt = builder.Configuration    .GetSection("Jwt")    .Get<JwtOptions>()!; builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)    .AddJwtBearer(options =>    {        options.TokenValidationParameters = new TokenValidationParameters        {            ValidateIssuerSigningKey = true,            IssuerSigningKey = new SymmetricSecurityKey(                Encoding.UTF8.GetBytes(jwt.SigningKey)),            ValidateIssuer = true,            ValidIssuer = jwt.Issuer,            ValidateAudience = true,            ValidAudience = jwt.Audience,            ValidateLifetime = true,            ClockSkew = TimeSpan.FromSeconds(30),            RoleClaimType = ClaimTypes.Role,            NameClaimType = ClaimTypes.Email        };    }); builder.Services.AddAuthorizationBuilder()    .AddPolicy("CanManageCatalog", policy =>        policy.RequireRole("Admin", "CatalogManager"))    .AddPolicy("ActiveUser", policy =>        policy.RequireAuthenticatedUser()              .RequireClaim("active", "true")); builder.Services.AddControllers(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();

UseAuthentication() reads and validates the token and builds HttpContext.User. UseAuthorization() evaluates the rules required by the endpoint. Authentication must run before authorization; otherwise the authorization layer may see an empty or unauthenticated user.

Registration and login endpoints

The registration endpoint should check for duplicate email addresses, hash the password, and never return the hash. The login endpoint should avoid revealing whether an email exists, because detailed errors can help attackers enumerate accounts.

[ApiController] [Route("api/auth")] public sealed class AuthController(    AppDbContext db,    PasswordService passwords,    JwtTokenService tokens) : ControllerBase {    [HttpPost("register")]    [AllowAnonymous]    public async Task<IActionResult> Register(        RegisterRequest request,        CancellationToken cancellationToken)    {        var email = request.Email.Trim().ToLowerInvariant();        var exists = await db.Users.AnyAsync(            x => x.Email == email, cancellationToken);        if (exists)            return Conflict(new { message = "Email is already registered." });        var user = new User        {            Id = Guid.NewGuid(),            Email = email,            Role = "User"        };        user.PasswordHash = passwords.Hash(user, request.Password);        db.Users.Add(user);        await db.SaveChangesAsync(cancellationToken);        return StatusCode(StatusCodes.Status201Created);    }    [HttpPost("login")]    [AllowAnonymous]    public async Task<ActionResult<LoginResponse>> Login(        LoginRequest request,        CancellationToken cancellationToken)    {        var email = request.Email.Trim().ToLowerInvariant();        var user = await db.Users.SingleOrDefaultAsync(            x => x.Email == email && x.IsActive,            cancellationToken);        if (user is null || !passwords.Verify(            user, request.Password, user.PasswordHash))            return Unauthorized(new { message = "Invalid credentials." });        return Ok(tokens.CreateToken(user));    } }

Use the validation layer from the previous lesson for password length, email format, and password policy rules. These rules should not become scattered throughout controller actions.

Protecting endpoints with roles

Applying only [Authorize] requires a valid authenticated identity. For role restrictions, use the Roles property.

[ApiController] [Route("api/products")] [Authorize] public sealed class ProductsController : ControllerBase {    [HttpGet]    public IActionResult GetProducts() => Ok();    [HttpDelete("{id:guid}")]    [Authorize(Roles = "Admin")]    public IActionResult DeleteProduct(Guid id) => NoContent();    [HttpPost]    [Authorize(Policy = "CanManageCatalog")]    public IActionResult CreateProduct() => StatusCode(201); }

The GET endpoint is available to any authenticated user, deletion is limited to the Admin role, and creation is allowed for either Admin or CatalogManager through the policy. Multiple roles specified in one authorization declaration generally mean “one of these roles.” Prefer policies for more complex conditions.

Resource ownership: roles are not enough

“The user is authenticated” or “the user is not an Admin” is not always sufficient. For example, a user may read only their own orders. Compare the resource owner ID with the user ID from the validated token, and centralize this rule in an application service or authorization handler when it is reused.

[HttpGet("{id:guid}")] [Authorize] public async Task<IActionResult> GetOrder(Guid id) {    var userIdValue = User.FindFirstValue(ClaimTypes.NameIdentifier);    if (!Guid.TryParse(userIdValue, out var userId))        return Unauthorized();    var order = await db.Orders        .SingleOrDefaultAsync(x => x.Id == id);    if (order is null)        return NotFound();    if (order.UserId != userId && !User.IsInRole("Admin"))        return Forbid();    return Ok(order); }

In this example, an invalid token or missing identity claim results in 401 Unauthorized. An authenticated user who is not allowed to access the resource receives 403 Forbidden. In some systems, returning 404 for unauthorized resource ownership checks is a deliberate security choice to avoid revealing whether the resource exists.

Common mistakes

  • Disabling validation: Validate the signature, issuer, audience, and lifetime rather than checking only that a token exists.
  • Long-lived access tokens: A leaked token remains useful for too long. Prefer short-lived access tokens and a secure refresh-token strategy.
  • Plain-text passwords: Use a dedicated password hasher or ASP.NET Core Identity.
  • Role claim mismatch: If the token uses one role claim type while validation expects another, [Authorize(Roles = ...)] may fail.
  • Trusting a client-supplied userId: Derive the current user from validated token claims, not from the request body.
  • Assuming JWTs are encrypted: Base64Url encoding does not provide confidentiality. Do not put sensitive information in the payload and always use HTTPS.
  • Protecting only the UI: Hiding a menu is not security. Authorization must be enforced by the API.

Practice exercise

  1. Create the Users table and PasswordHash column, and add a unique index for email.
  2. Implement POST /api/auth/register and POST /api/auth/login.
  3. Configure JWT bearer validation in Program.cs and verify the middleware order.
  4. Create GET /api/profile for authenticated users. Read the email and user ID from User.Claims.
  5. Add one delete endpoint requiring the Admin role and one create endpoint requiring the CanManageCatalog policy.
  6. Test a valid token, an expired token, a request without a token, an insufficient role, and access to another user’s resource.

Conclusion

The essential JWT authentication flow consists of securely hashing passwords, issuing a token, validating the token, and protecting endpoints with authorization rules. Role-based authorization is quick for simple access decisions. Policy-based authorization provides a more maintainable way to combine roles, claims, and custom business rules.

In a production API, evaluate authentication together with resource ownership, tenant boundaries, refresh-token security, audit logging, centralized error responses, and external identity providers. This turns authentication from an isolated middleware configuration into a clearly defined security boundary that clients can reliably consume.

Sources