Security: Authentication and Authorization

7 min read

Welcome to the fortress. 🏰

If you have built an API that does anything interesting, eventually someone will try to break it. Or, more benignly, you simply need to know who is talking to your server so you can save their specific data.

In the physical world, security is often reactive. In software, it must be proactive. We are moving from "Make it work" to "Make it safe."

Today, we delve into the rigorous academic standards of securing an ASP.NET Core application. We will construct a system that verifies identity and enforces permissions with mathematical precision.


1. Identity Core Concepts: Who Are You vs. What Can You Do?

Before writing code, we must strictly define our terminology. In the industry, these two terms are often used interchangeably by novices. You are no longer a novice.

The Definitions

Authentication (AuthN)
This is the process of verifying the identity of a user or service. It answers the question: Who are you?

  • Problem: The server receives a request (e.g., "Delete Database"). It needs to know the origin of this request.
  • Solution: Credentials (passwords, biometrics, keys) are exchanged for a verified Identity.

Authorization (AuthZ)
This is the process of determining what the verified identity is allowed to do. It answers the question: Are you allowed to be here?

  • Problem: Just because we know who you are (AuthN) doesn't mean you should have access to the payroll system.
  • Solution: Rules, Roles, and Policies checks against the Identity.

Interesting Fact: The "N" in AuthN and the "Z" in AuthZ are used as shorthand because "Authentication" and "Authorization" look nearly identical when you are scanning logs at 3:00 AM. 🦉

The ASP.NET Core Abstraction: Claims

In ASP.NET Core, an identity is not just a user ID. It is a collection of Claims.

A Claim is a key-value pair that represents a fact about the subject.

Think of a driver's license. It contains multiple claims: your photo (claim), your birthdate (claim), and your license number (claim). The license itself is the Identity (ClaimsIdentity), and you holding it makes you the Principal (ClaimsPrincipal).


2. Issuing Passports: Implementing JWT (JSON Web Tokens) Authentication

The Definition

A JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

The Problem: Statelessness

In traditional web apps, the server keeps a record of logged-in users in memory (Session).

  • If the server restarts, everyone is logged out.
  • If you scale to 5 servers, Server A doesn't know the user logged into Server B.

The Solution

JWTs are stateless. The token is the session. The server issues a token signed with a secret key. When the client sends the token back, the server only needs the key to verify it. No database lookup is required to check if the user is "logged in."

Industry Standard Implementation

We will use the Microsoft.AspNetCore.Authentication.JwtBearer package.

Step 1: Install Dependencies

Open your terminal in the project folder:

bash
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 2: Configure appsettings.json

You need a secret key. In production, this goes in Azure KeyVault or AWS Secrets Manager. For now, we place it here.
Note: The key must be at least 32 characters long to be secure for HmacSha256.

json
{
  "Jwt": {
    "Key": "ThisIsMySuperSecretKeyThatIsLongEnough123!",
    "Issuer": "https://myserver.com",
    "Audience": "https://myclient.com"
  }
}

Step 3: Register Services (Program.cs)

We must inform the Dependency Injection container that we are using JWTs.

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

var builder = WebApplication.CreateBuilder(args);

// 1. Add Authentication Services
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"]))
    };
});

var app = builder.Build();

// 2. Add Middleware (ORDER MATTERS STRICTLY)
app.UseHttpsRedirection();

app.UseAuthentication(); // Who are you?
app.UseAuthorization();  // What can you do?

app.MapControllers();

app.Run();

Warning: If you swap the order of UseAuthentication and UseAuthorization, your security will fail silently. You must know who someone is before you check their permissions.

Step 4: Generating the Token (Login Controller)

Here is a strictly academic example of a login method returning a token.

csharp
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel login)
{
    // 1. Validate User (Mock database check)
    if (login.Username == "admin" && login.Password == "password123")
    {
        // 2. Create Claims
        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Sub, login.Username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.Role, "Admin") // Adding a role for later
        };

        // 3. Create Signing Key
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        // 4. Generate Token
        var token = new JwtSecurityToken(
            issuer: _configuration["Jwt:Issuer"],
            audience: _configuration["Jwt:Audience"],
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds
        );

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

    return Unauthorized();
}

3. Role-Based Authorization: Restricting Access by User Groups

The Definition

Role-Based Access Control (RBAC) restricts network access based on the roles of individual users within an enterprise.

The Problem

You have an endpoint DELETE /api/users/all. You do not want a regular user to hit this.

The Solution

We attach the [Authorize] attribute with a specific Roles parameter. The middleware checks the ClaimTypes.Role inside the JWT we generated earlier.

Implementation

In your Controller:

csharp
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    // Accessible by anyone with a valid Token (Logged in)
    [HttpGet]
    [Authorize] 
    public IActionResult GetAll() 
    {
        return Ok("Here are products");
    }

    // Accessible ONLY by users with "Admin" role claim
    [HttpDelete]
    [Authorize(Roles = "Admin")]
    public IActionResult DeleteAll()
    {
        return Ok("Database purged.");
    }
}

If a user with a valid token (but no "Admin" role) tries to access DeleteAll, the server will strictly return 403 Forbidden.

  • 401 Unauthorized: I don't know who you are (Token missing/invalid).
  • 403 Forbidden: I know who you are, but you aren't allowed here.

4. Policy-Based Authorization: Fine-Grained Access Control

The Definition

Policy-based authorization decouples authorization logic from the underlying roles. It creates requirements based on claims logic.

The Problem

Roles are too broad.
Imagine a requirement: "Only users who are Employees AND were hired before 2020 can access the archives."
Creating a role called SeniorEmployeeBefore2020 is messy and unsustainable.

The Solution

We define a Policy. A policy is a collection of requirements.

Implementation

Step 1: Define the Policy in Program.cs

csharp
builder.Services.AddAuthorization(options =>
{
    // Policy 1: Must be an Admin
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));

    // Policy 2: Must use a company email domain
    options.AddPolicy("EmployeesOnly", policy => 
        policy.RequireClaim(ClaimTypes.Email)
              .RequireAssertion(context => 
                  context.User.HasClaim(c => c.Type == ClaimTypes.Email && 
                                             c.Value.EndsWith("@company.com"))
              ));
});

Step 2: Apply the Policy

Instead of specifying roles, we specify the policy name.

csharp
[HttpGet("company-secrets")]
[Authorize(Policy = "EmployeesOnly")]
public IActionResult GetSecrets()
{
    return Ok("The secret ingredient is butter.");
}

Imagination: Think of Policy-Based Auth as a custom script for a bouncer. RBAC is "VIPs only." Policy is "VIPs who are wearing blue shoes and know the secret handshake." 🕵️‍♂️


Summary

We have traveled from the philosophical concept of Identity to the concrete implementation of JWTs and granular Access Control policies.

  1. AuthN identifies the user.
  2. AuthZ validates the user's permissions.
  3. JWTs provide a stateless, portable mechanism for carrying this data.
  4. Policies allow for complex logic beyond simple roles.

Security is not a feature; it is the foundation. Build it strong.

📚 References & Further Reading

Challenge

Challenge: Implement Advanced Policy-Based Authorization

You are tasked with securing a sensitive API endpoint in an internal HR application. The endpoint, GetPerformanceReview, should only be accessible to specific users based on a complex set of rules.

Your goal is to configure the application's services in Program.cs to use JWT Bearer authentication and add a custom authorization policy named CanViewPerformanceReview.

This policy must enforce the following three requirements simultaneously:

  1. The user must have the role of "Manager".
  2. The user must possess a "Department" claim with the value "HR".
  3. The user's "EmployeeId" claim must be a numeric value less than 5000. This requires using a custom assertion.

Finally, apply this policy to the GetPerformanceReview action in the PerformanceController.

Instructions:

  1. In the provided Program.cs code, add the necessary services for JWT Bearer authentication.
  2. Add and configure the authorization services to define the CanViewPerformanceReview policy with all the specified requirements.
  3. Ensure the middleware pipeline is correctly ordered.
  4. Apply the newly created policy to the controller action.

Expected result

The solution must be a valid C# code block that correctly configures the services and middleware in a minimal ASP.NET Core application.

The expected output should contain the following elements:

  1. JWT Authentication Service: A call to builder.Services.AddAuthentication() that configures JwtBearerDefaults.AuthenticationScheme.

    • Inside, AddJwtBearer should be called, setting TokenValidationParameters.
    • Key properties like ValidateIssuer, ValidateAudience, ValidateLifetime, and ValidateIssuerSigningKey should be set to true.
    • ValidIssuer, ValidAudience, and IssuerSigningKey can be set with placeholder or example values (e.g., from builder.Configuration).
  2. Authorization Service and Policy Definition: A call to builder.Services.AddAuthorization().

    • Inside the options lambda, a policy named "CanViewPerformanceReview" must be added using options.AddPolicy().
    • The policy builder must chain the three required rules:
      • policy.RequireRole("Manager")
      • policy.RequireClaim("Department", "HR")
      • policy.RequireAssertion(context => ...)
    • The RequireAssertion lambda must correctly retrieve the "EmployeeId" claim, parse it as an integer, and return true if the value is less than 5000.
  3. Middleware Configuration: The app.UseAuthentication() and app.UseAuthorization() methods must be called after app.UseHttpsRedirection() and in that specific order.

  4. Controller Attribute: The GetPerformanceReview method within the PerformanceController class must be decorated with the attribute [Authorize(Policy = "CanViewPerformanceReview")].

csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.