🔐 Authentication & Authorization in ASP.NET Core (JWT, Roles & Policies)

Samim.Hossain
Samim Hossain
Published on Feb, 15 2026 2 min read 0 comments
image

Introduction

Security is not optional in modern applications.
Whether you are building a public API, SaaS platform, or mobile backend, authentication and authorization are critical.

In ASP.NET Core, security is:

  • Powerful
  • Flexible
  • Production-ready

In this article, you’ll learn how authentication and authorization really work, with JWT-based authentication, roles, and policies—exactly how real-world systems are built.

This is Week 7 of our .NET weekly blog series.

Authentication vs Authorization (Very Important)

Many beginners confuse these two concepts.

| Term           | Meaning                     |
| -------------- | --------------------------- |
| Authentication | Who are you?                |
| Authorization  | What are you allowed to do? |

📌 Example:

  • Login → Authentication
  • Admin-only access → Authorization

Authentication in ASP.NET Core

Authentication verifies a user’s identity using:

  • Username & password
  • Tokens (JWT)
  • Cookies
  • OAuth (Google, Facebook, etc.)

In modern APIs, JWT (JSON Web Token) is the most popular choice.

What Is JWT (JSON Web Token)?

A JWT is a secure token that contains:

  • User identity
  • Claims (role, permissions)
  • Expiry time

JWT Structure

Header.Payload.Signature

✔ Stateless
✔ Fast
✔ Scales well

JWT Authentication Flow

1️⃣ User logs in with credentials
2️⃣ Server validates credentials
3️⃣ Server generates JWT
4️⃣ Client stores JWT
5️⃣ Client sends JWT in Authorization header
6️⃣ Server validates token on every request

Step 1: Install Required Packages

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 2: Configure JWT in Program.cs

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "myapp",
            ValidAudience = "myapp",
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes("SUPER_SECRET_KEY_123")
            )
        };
    });

app.UseAuthentication();
app.UseAuthorization();

⚠️ Secret keys should be stored securely (env variables).

Step 3: Generate JWT Token

public string GenerateToken(string username, string role)
{
    var claims = new[]
    {
        new Claim(ClaimTypes.Name, username),
        new Claim(ClaimTypes.Role, role)
    };

    var key = new SymmetricSecurityKey(
        Encoding.UTF8.GetBytes("SUPER_SECRET_KEY_123")
    );

    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: "myapp",
        audience: "myapp",
        claims: claims,
        expires: DateTime.Now.AddHours(2),
        signingCredentials: creds
    );

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

Step 4: Secure Your API Endpoints

Protect Controller

[Authorize]
[ApiController]
[Route("api/profile")]
public class ProfileController : ControllerBase
{
    [HttpGet]
    public IActionResult GetProfile()
    {
        return Ok("Secure profile data");
    }
}

Now this endpoint requires a valid JWT.

Role-Based Authorization

Roles allow access control like:

Admin

User

Manager

Role-Based Example

[Authorize(Roles = "Admin")]
[HttpDelete("delete")]
public IActionResult Delete()
{
    return Ok("Admin-only action");
}

✔ Simple
✔ Effective

Policy-Based Authorization (Advanced)

Policies provide fine-grained control.

Define Policy

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy =>
        policy.RequireRole("Admin"));
});

Use Policy

[Authorize(Policy = "AdminOnly")]
public IActionResult SecureAction()
{
    return Ok("Admin policy applied");
}

✔ More flexible
✔ Scales better than roles alone

Claims-Based Authorization

Claims carry extra information inside JWT.

Example claims:

  • Email
  • Subscription type
  • Permissions
new Claim("Subscription", "Premium")
policy.RequireClaim("Subscription", "Premium");

Common Security Mistakes 🚫

  • Hardcoding secret keys
  • Not validating token expiration
  • Returning sensitive data
  • Overusing roles
  • Skipping HTTPS

Best Practices ✅

  • Always use HTTPS
  • Store secrets in environment variables
  • Use short token lifetimes
  • Refresh tokens securely
  • Log authentication failures

What You’ve Learned

✔ Authentication vs Authorization
✔ JWT authentication flow
✔ Securing APIs
✔ Role-based authorization
✔ Policy-based authorization

You now understand real-world ASP.NET Core security 🔐

 

 

🔜 Coming Next

User Management & Identity (ASP.NET Core Identity)

You’ll learn:

  • User registration & login
  • Password hashing
  • Roles & claims
  • Identity + JWT integration

 

0 Comments