LESSON 14 OF 16

14. Authentication, Authorization, and Secure API Design

Learn how to implement JWT authentication, role- and policy-based authorization, and essential security practices in an ASP.NET Core REST API.

50 dk 97

Introduction

In the previous lesson, we connected the web application to the REST API. Making that communication work is only part of the solution. We must also decide who may access the API, which operations each user may perform, and how every request is validated. In this lesson, we will add authentication and authorization to the three-tier architecture.

Authentication determines who is making a request. Authorization determines whether that authenticated identity is allowed to access a resource or perform an operation. For example, a user may sign in successfully, while only a user with the Admin role may delete an order.

Our example uses JWT Bearer authentication in the API. After signing in, the web application sends the access token in the Authorization header of subsequent API requests. The API validates the token signature, issuer, audience, and lifetime, then evaluates role or policy requirements.

The Authentication and Authorization Flow

  1. The user submits credentials to the web application or to the API login endpoint.
  2. The credentials are validated by an application authentication service.
  3. If validation succeeds, the service issues an access token.
  4. The web application sends the token with later API requests using the Bearer scheme.
  5. JWT middleware validates the token and creates the user principal in HttpContext.User.
  6. Authorization middleware evaluates roles, claims, and policies.
  7. If access is granted, the controller calls the Business layer and the normal three-tier flow continues.

A failed or missing credential generally produces 401 Unauthorized. An authenticated user who lacks the required permission generally receives 403 Forbidden. Keeping these cases separate is important for client behavior, diagnostics, and security monitoring.

Configuring JWT Bearer Authentication

Add the appropriate Microsoft.AspNetCore.Authentication.JwtBearer package to the API project. In production, token issuance should normally be delegated to a trusted identity provider, ASP.NET Core Identity, or an OAuth 2.0/OpenID Connect-compatible identity service. The following example demonstrates a simple educational validation setup inside the API.

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

var jwtKey = builder.Configuration["Jwt:Key"]
    ?? throw new InvalidOperationException("JWT key is missing.");

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidateAudience = true,
            ValidAudience = builder.Configuration["Jwt:Audience"],
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(1)
        };
    });

builder.Services.AddAuthorization();
builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Middleware order matters. UseAuthentication identifies the caller, while UseAuthorization checks whether that identity is allowed to access the endpoint. Both calls must appear before endpoint mappings.

Do not place the JWT key in source control. Use User Secrets during development, environment variables where appropriate, and a managed secrets solution in production. A short, predictable, or publicly committed key cannot protect an API reliably.

Login Endpoint and Claims

In a three-tier solution, a controller should not contain the details of password verification or token construction. The controller should receive a DTO, call an authentication service in the Business layer, and translate the result into an HTTP response. A simple contract might look like this:

public sealed record LoginRequest(string Email, string Password);
public sealed record LoginResponse(string AccessToken, DateTime ExpiresAtUtc);

The following method illustrates token creation for training purposes. In a real application, passwords must never be compared as plain text. Use a well-tested password hashing mechanism or a complete identity solution.

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;

public string CreateToken(Guid userId, string email, string role)
{
    var claims = new List<Claim>
    {
        new(JwtRegisteredClaimNames.Sub, userId.ToString()),
        new(JwtRegisteredClaimNames.Email, email),
        new(ClaimTypes.Role, role),
        new("permission", "orders.read")
    };

    var key = new SymmetricSecurityKey(
        Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]!));
    var credentials = new SigningCredentials(
        key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: _configuration["Jwt:Issuer"],
        audience: _configuration["Jwt:Audience"],
        claims: claims,
        expires: DateTime.UtcNow.AddMinutes(30),
        signingCredentials: credentials);

    return new JwtSecurityTokenHandler().WriteToken(token);
}

Claims carry identity and permission information with the request. Do not put passwords, sensitive personal data, or large and frequently changing datasets into a token. Claims do not automatically change after a token is issued, so short-lived access tokens and, when necessary, a carefully designed refresh-token strategy should be considered.

Protecting API Endpoints

Adding [Authorize] to a controller or action requires an authenticated user through the default authentication scheme:

[ApiController]
[Route("api/orders")]
[Authorize]
public class OrdersController : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetAll(CancellationToken cancellationToken)
    {
        var result = await _orderService.GetAllAsync(cancellationToken);
        return Ok(result);
    }

    [HttpPost]
    [Authorize(Roles = "Admin,Sales")]
    public async Task<IActionResult> Create(
        CreateOrderRequest request,
        CancellationToken cancellationToken)
    {
        var result = await _orderService.CreateAsync(request, cancellationToken);
        return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
    }

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> GetById(Guid id,
        CancellationToken cancellationToken)
    {
        var result = await _orderService.GetByIdAsync(id, cancellationToken);
        return result is null ? NotFound() : Ok(result);
    }
}

Use [AllowAnonymous] only for endpoints that genuinely need to be public, such as login, token renewal, or a health check. Applying [Authorize] at controller level reduces the risk that a newly added action is accidentally exposed.

Role-Based and Policy-Based Authorization

Role-based authorization directly checks a role assigned to the user. Roles such as Admin, Sales, and ReadOnly are convenient for small and stable permission models. As the application grows, relying only on role names can make access rules difficult to evolve.

Policy-based authorization allows more expressive rules based on claims, requirements, or custom handlers:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("CanReadOrders", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("permission", "orders.read");
    });

    options.AddPolicy("CanManageOrders", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireRole("Admin", "Sales");
        policy.RequireClaim("permission", "orders.manage");
    });
});

Apply a policy to an endpoint like this:

[HttpGet]
[Authorize(Policy = "CanReadOrders")]
public async Task<IActionResult> GetForAuthorizedUser(
    CancellationToken cancellationToken)
{
    var result = await _orderService.GetAllAsync(cancellationToken);
    return Ok(result);
}

Authorization at the controller is an important boundary, but resource ownership rules should also be enforced in the Business layer. If a user may see only their own orders, the service should compare the user identifier from a validated claim with the owner identifier of the order. Hiding a button in the web interface is not a security control; an attacker can call the endpoint directly.

Sending the Token from the Web Application

The web application sends the access token in this HTTP header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6...

For a server-side web application, keeping the token in a protected server session or an appropriately protected cookie may be safer than exposing it to browser JavaScript. If cookie authentication is used, configure CSRF protections, SameSite behavior, and the Secure and HttpOnly options carefully.

When the API is protected with JWT rather than cookies, a centralized HttpClient service or delegating handler can add the access token to outgoing requests. If no token is available, the client should avoid calling protected endpoints. Responses such as 401 and 403 should be handled explicitly and mapped to an appropriate user experience.

Essential API Security Measures

  • Use HTTPS: Never send passwords or access tokens over unencrypted HTTP.
  • Validate tokens completely: Do not disable signature, issuer, audience, or lifetime validation.
  • Protect secrets: Do not place keys in source code, committed configuration files, or logs.
  • Hash passwords: Never store plain-text passwords or invent custom cryptography.
  • Validate input: Apply DTO validation, request-size limits, and allowed-value checks.
  • Prevent SQL injection: Preserve parameterized queries and ORM safeguards; never concatenate user input into SQL text.
  • Restrict CORS: In production, allow known web application origins instead of every origin.
  • Consider rate limiting: Protect login, token renewal, and expensive query endpoints from abuse.
  • Keep logs clean: Never log access tokens, passwords, or unnecessary sensitive claims.
  • Secure by default: Require authentication broadly and explicitly mark only genuinely public endpoints as anonymous.

Common Mistakes

  • Omitting authentication middleware: Registering AddAuthentication without calling UseAuthentication prevents the expected user principal from being established.
  • Confusing 401 and 403: An invalid or missing token normally leads to 401; an authenticated user without permission normally leads to 403.
  • Trusting only the UI: Hiding a menu item or button does not replace endpoint authorization.
  • Relaxing validation: Disabling signature or lifetime checks removes the trust boundary provided by the token.
  • Using long-lived tokens: A stolen token can remain useful for a long time. Plan short-lived access tokens and revocation strategies.
  • Accepting user identity from the request body: Read the user identifier from validated claims instead of trusting a client-supplied UserId.

Short Practice Exercise

Extend the existing order API with these requirements:

  1. Create LoginRequest and LoginResponse DTOs for POST /api/auth/login.
  2. On successful login, issue a short-lived JWT containing the user identifier, email, role, and the orders.read claim.
  3. Protect the orders controller by default with [Authorize].
  4. Apply a CanReadOrders policy to listing and a CanManageOrders policy to creation and deletion.
  5. Verify that the web application sends the Authorization: Bearer header.
  6. Write three tests covering an invalid token, a missing role or permission, and a successful authorized request.

Conclusion

This lesson demonstrated that API security is more than a login page. Authentication establishes identity, while authorization evaluates permissions. JWT middleware validates the incoming token, roles and policies restrict endpoint access, and the Business layer must re-check resource-specific rules such as ownership.

In the next stage, this security design should be evaluated together with automated tests, centralized error handling, observability, and production deployment. A secure three-tier application keeps responsibilities clear: the API protects access boundaries, the Business layer applies permission-sensitive rules, and the Data layer accesses data only through authorized application operations.

Sources