Authentication and Authorization in ASP.NET Core

What is Authentication?

Authentication is the process of verifying who the user is.

It ensures the user’s identity is valid, typically through:

  • Username/Password
  • Tokens (e.g., JWT)
  • Cookies
  • External providers (Google, Facebook, Azure AD)

Example: If you log in using your email and password, that’s authentication. If your credentials are correct, the server "knows" who you are.

2. What is Authorization?

Authorization is the process of determining what an authenticated user is allowed to do.

After you are authenticated:

  • Are you allowed to access this endpoint?
  • Do you have the required role?
  • Do you have permission to perform a certain action?

What happens when the user logs in?

  • User submits credentials via login form or API (e.g., /login)
  • Backend validates the credentials (e.g., against a database)
  • If valid, the server issues an authentication token (JWT or sets a cookie).
  • On the next request, the client sends the token or cookie back
  • The middleware validates it and sets the User. Identity
  • Controllers/actions protected by [Authorize] now recognize the user

Example: JWT Authentication (API-Based)

Step 1. Add JWT Authentication Packages.

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 2: Configure Authentication in the Program.cs.
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "your-app",
            ValidateAudience = true,
            ValidAudience = "your-client",
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes("your-secret-key")),
            ValidateLifetime = true
        };
    });

builder.Services.AddAuthorization();

Then in middleware:
var app = builder.Build();

app.UseAuthentication();   // Must be before UseAuthorization
app.UseAuthorization();

app.MapControllers();

Step 3: Login Endpoint: Validate Credentials and Generate Token
[HttpPost("login")]
public IActionResult Login(LoginModel model)
{
    if (model.Username == "admin" && model.Password == "password") // DB check in real case
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, model.Username),
            new Claim(ClaimTypes.Role, "Admin")
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: "your-app",
            audience: "your-client",
            claims: claims,
            expires: DateTime.Now.AddHours(1),
            signingCredentials: creds);

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

    return Unauthorized("Invalid credentials");
}

Step 4: Client Sends JWT in Authorization Header
On every request to a protected API:
GET /api/secure-data
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Step 5: Use [Authorize] to Protect Routes
[Authorize]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
    var username = User.Identity?.Name;
    return Ok($"This data is only visible to {username}");
}

How does it work behind the Scenes?

Step 1: Authentication Middleware checks the incoming request
Step 2: Look for a valid Authorization header (with JWT)
Step 3: If valid:
  • It decodes the token
  • Sets HttpContext.User with claims and identity
Step 4: Then, [Authorize] uses this info to allow or deny access

[Authorize] → Requires the user to be authenticated
[AllowAnonymous] → Bypasses authorization for that method

JWT Token Structure.

A JWT token is made of 3 parts:
  • HEADER
  • PAYLOAD
  • SIGNATURE
1. HEADER
The Header contains metadata about the token:
{
  "alg": "HS256",   // Algorithm used (HMAC SHA-256)
  "typ": "JWT"      // Token type
}

2. PAYLOAD (this is where all your data is)
This is the main body of the JWT. It contains:
  • iss Issuer – who created the token
  • aud Audience – who the token is for
  • exp Expiration time (Unix timestamp)
  • nbf Not before – token valid after this time
  • iat Issued at time
  • sub Subject – usually the user ID
  • jti Token ID – unique identifier
Example:
{
  "iss": "JwtAuthDemo",
  "aud": "JwtAuthClient",
  "exp": 1720542515,
  "sub": "123456"
}

Custom Claims (You define these!)
These are the claims you add for user info, roles, etc.

Example:
{
  "name": "admin",
  "email": "admin@example.com",
  "role": "Admin",
  "department": "HR"
}

ASP.NET Core reads the role claim automatically for [Authorize(Roles = "...")].

3. SIGNATURE
Signature is used to validate the token’s integrity using your secret key.
It's computed like this:
HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret-key
)

If someone tries to tamper with the payload, the signature won’t match anymore.

Note: JWT is not encrypted, just base64-encoded. Never store sensitive information like passwords in it.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS