LESSON 18 OF 22

18. Authentication and Authorization Integration

Add secure password handling, JWT authentication, role- and policy-based authorization, and protected API endpoints to the Clean Architecture solution.

40 dk 120

Introduction

In this lesson, we will add user authentication and authorization to the Clean Architecture solution built in the previous lessons. The goal is not only to make an endpoint require a token, but to place each security responsibility in the correct layer.

Authentication verifies who is making a request. Authorization determines whether that authenticated identity is allowed to perform a specific action or access a resource. A user may successfully sign in and still be forbidden from accessing an administrator-only endpoint.

We will store passwords as secure hashes rather than plain text, create JWT access tokens after a successful login, validate those tokens in the API, and use role- or policy-based rules to protect endpoints.

Authentication establishes identity; authorization evaluates permissions. Configuring one does not automatically configure the other.

Assigning Responsibilities to Layers

Security crosses the entire application, but the responsibilities should remain separated:

  • Domain: Represents business concepts such as users and roles without depending on HTTP, JWT, or ASP.NET Core.
  • Application: Defines registration, login, and current-user use cases. It owns abstractions for password handling and token creation.
  • Infrastructure: Implements the user repository, password hashing provider, and JWT token service.
  • Presentation/API: Configures authentication middleware, authorization policies, and protected controllers.

This structure prevents the Application layer from becoming coupled to a specific JWT package. If token issuance later moves to an external identity provider, the use case can continue to depend on the same application contract.

User Entity and Password Storage

Let us define a simple user entity in the Domain layer. A production system may also include email verification, account lockout, password-change timestamps, refresh-token metadata, and audit information.

public sealed class User : Entity<Guid>
{
    private User() { }

    public User(string email, string passwordHash, string role)
    {
        Id = Guid.NewGuid();
        Email = email.Trim().ToLowerInvariant();
        PasswordHash = passwordHash;
        Role = role;
        IsActive = true;
    }

    public string Email { get; private set; } = string.Empty;
    public string PasswordHash { get; private set; } = string.Empty;
    public string Role { get; private set; } = "User";
    public bool IsActive { get; private set; }
}

Passwords must never be stored as plain text. A password hashing algorithm should use a salt and a work factor so that offline guessing is expensive. ASP.NET Core provides the IPasswordHasher<TUser> abstraction, including methods for creating and verifying password hashes.

To avoid coupling the Application layer to the framework abstraction, define an application-level contract:

public interface IPasswordService
{
    string Hash(string password);
    bool Verify(string password, string passwordHash);
}

An Infrastructure implementation can delegate to ASP.NET Core’s password hasher:

public sealed class PasswordService : IPasswordService
{
    private readonly IPasswordHasher<PasswordUser> _hasher;

    public PasswordService(IPasswordHasher<PasswordUser> hasher)
    {
        _hasher = hasher;
    }

    public string Hash(string password)
    {
        return _hasher.HashPassword(new PasswordUser(), password);
    }

    public bool Verify(string password, string passwordHash)
    {
        var result = _hasher.VerifyHashedPassword(
            new PasswordUser(), passwordHash, password);

        return result == PasswordVerificationResult.Success ||
               result == PasswordVerificationResult.SuccessRehashNeeded;
    }

    private sealed class PasswordUser { }
}

The small private type is used as the generic user type for the password hasher. Using the Domain User entity is also possible. The important rule is that password hashing should not be performed inside a controller or embedded directly in an entity.

Application Authentication Use Cases

Create request and response DTOs for registration and login:

public sealed record RegisterRequest(string Email, string Password);
public sealed record LoginRequest(string Email, string Password);
public sealed record AuthResponse(Guid UserId, string Email, string Role, string AccessToken);

Token creation should also be represented by an Application abstraction:

public interface ITokenService
{
    string CreateAccessToken(User user);
}

The login use case retrieves the user, checks that the account is active, verifies the password, and creates a token only after successful verification:

public sealed class AuthenticationService : IAuthenticationService
{
    private readonly IUserRepository _users;
    private readonly IPasswordService _passwords;
    private readonly ITokenService _tokens;

    public AuthenticationService(
        IUserRepository users,
        IPasswordService passwords,
        ITokenService tokens)
    {
        _users = users;
        _passwords = passwords;
        _tokens = tokens;
    }

    public async Task<AuthResponse> LoginAsync(
        LoginRequest request,
        CancellationToken cancellationToken)
    {
        var user = await _users.GetByEmailAsync(
            request.Email, cancellationToken);

        if (user is null || !user.IsActive ||
            !_passwords.Verify(request.Password, user.PasswordHash))
        {
            throw new ApplicationException("Invalid email or password.");
        }

        var token = _tokens.CreateAccessToken(user);
        return new AuthResponse(user.Id, user.Email, user.Role, token);
    }
}

Returning the same error for an unknown email and an incorrect password avoids revealing which email addresses exist in the database. The application service can later be connected to the validation and centralized error handling mechanisms created in earlier lessons.

JWT Options and Token Creation

JWT settings should be loaded through configuration instead of being embedded in source code:

"Jwt": {
  "Issuer": "CleanArchitecture.Api",
  "Audience": "CleanArchitecture.Client",
  "Key": "development-only-change-this-key-01234567890123456789",
  "AccessTokenMinutes": 30
}

The sample key is suitable only for local development. Production secrets should be stored in a secret-management system such as an environment-specific secret store or a managed vault. The signing key must be long, random, protected, and accessible only to trusted services.

The Infrastructure token service can create a signed access token:

public sealed class JwtTokenService : ITokenService
{
    private readonly JwtOptions _options;

    public JwtTokenService(IOptions<JwtOptions> options)
    {
        _options = options.Value;
    }

    public string CreateAccessToken(User user)
    {
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Email, user.Email),
            new Claim(ClaimTypes.Role, user.Role),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var key = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(_options.Key));
        var credentials = new SigningCredentials(
            key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: _options.Issuer,
            audience: _options.Audience,
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(
                _options.AccessTokenMinutes),
            signingCredentials: credentials);

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

JWT access tokens are signed but are not automatically encrypted. Do not place passwords, payment information, or other sensitive personal data in claims. Include only the identity and permission information required by the API.

Configuring JWT Authentication

After adding the JWT bearer package, configure token validation in Program.cs:

builder.Services.Configure<JwtOptions>(
    builder.Configuration.GetSection("Jwt"));

builder.Services.AddAuthentication(
    JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        var jwt = builder.Configuration
            .GetSection("Jwt").Get<JwtOptions>()!;

        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(jwt.Key)),
            ValidateIssuer = true,
            ValidIssuer = jwt.Issuer,
            ValidateAudience = true,
            ValidAudience = jwt.Audience,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(30)
        };
    });

builder.Services.AddAuthorization();

The API should validate the signature, issuer, audience, and lifetime. Disabling one of these checks can allow tokens created for another application, modified tokens, or expired tokens to be accepted.

Middleware order is significant:

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

UseAuthentication reads the token and constructs HttpContext.User. UseAuthorization then evaluates the authorization metadata for the selected endpoint.

Login and Protected Endpoints

The login action must be available without a token:

[ApiController]
[Route("api/auth")]
public sealed class AuthController : ControllerBase
{
    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<ActionResult<AuthResponse>> Login(
        LoginRequest request,
        CancellationToken cancellationToken)
    {
        var response = await _service.LoginAsync(
            request, cancellationToken);
        return Ok(response);
    }
}

Require authentication for an orders endpoint:

[ApiController]
[Route("api/orders")]
[Authorize]
public sealed class OrdersController : ControllerBase
{
    [HttpGet("mine")]
    public IActionResult GetMine()
    {
        var userId = User.FindFirstValue(
            ClaimTypes.NameIdentifier);
        return Ok(new { UserId = userId });
    }
}

The client sends the access token in the HTTP header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Role- and Policy-Based Authorization

Role-based authorization is useful for simple access rules:

[HttpDelete("{id:guid}")]
[Authorize(Roles = "Admin")]
public IActionResult Delete(Guid id)
{
    return NoContent();
}

Policies are better when access depends on a permission or a more expressive rule:

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("CanManageCatalog", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("permission", "catalog.manage");
    });
[HttpPost]
[Authorize(Policy = "CanManageCatalog")]
public IActionResult Create(CreateProductRequest request)
{
    return Created();
}

The token must contain the permission claim for this policy to succeed. However, authorization must never depend on untrusted values supplied by a client. Claims should be issued by a trusted token service, and changes to permissions should be considered when choosing token lifetimes or a token-revocation strategy.

If the API should be protected by default, configure a fallback policy:

builder.Services.AddAuthorizationBuilder()
    .SetFallbackPolicy(new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build());

With this configuration, only endpoints explicitly marked with [AllowAnonymous] remain public. Login, registration, health checks, or public metadata endpoints must be marked deliberately.

Understanding 401 and 403

StatusMeaningExample
401 UnauthorizedThe identity could not be authenticated.The token is missing, malformed, expired, or has an invalid signature.
403 ForbiddenThe identity is authenticated but lacks permission.A regular user attempts to access an Admin policy.

This distinction allows a client application to choose the correct response. A 401 may require sign-in or token renewal, while a 403 usually means that the user needs a different permission.

Common Mistakes

  • Storing passwords as plain text, Base64, or reversible encryption.
  • Committing a JWT signing key to source control.
  • Disabling issuer, audience, signature, or lifetime validation.
  • Calling UseAuthentication after UseAuthorization.
  • Accidentally protecting the login endpoint with [Authorize].
  • Putting passwords, payment data, or sensitive personal data in JWT claims.
  • Implementing authorization only in the frontend.
  • Returning different errors for an unknown account and an incorrect password.
  • Using very long-lived access tokens without a revocation or rotation strategy.

Practice Exercise

  1. Add Role and IsActive properties to the User entity.
  2. Create registration and login DTOs and validate email and password rules with FluentValidation.
  3. Add IPasswordService and ITokenService to the Application layer.
  4. Implement password hashing and JWT creation in Infrastructure.
  5. Keep /api/auth/login anonymous and protect an orders endpoint.
  6. Protect one action with [Authorize] and another with [Authorize(Roles = "Admin")].
  7. Use Swagger or an HTTP client to test a valid token, an expired token, and a token with an insufficient role.

Conclusion

In this lesson, we integrated authentication and authorization without mixing layer responsibilities. The Application layer defined use cases and abstractions, Infrastructure implemented password hashing and token generation, and the API configured JWT middleware and access rules.

Security is more than generating a token. Secure password storage, complete token validation, correct middleware order, short-lived access tokens, role or policy rules, and meaningful HTTP status codes must work together. In the next stage, these behaviors can be covered with automated tests for the authentication service and protected endpoints, making the security flow easier to maintain as the application grows.

Sources