SQL-and-NoSQL-database :👈 👉:Versioning in REST APIs

Authentication and Authorization in .NET Core

ASP.NET Core Authentication and Authorization: JWT, OAuth 2.0 and OpenID Connect

1. Introduction

Authentication and authorization are two important security concepts in ASP.NET Core applications.

Authentication verifies the identity of a user or application, while authorization determines what an authenticated user or application is allowed to access.

Modern ASP.NET Core applications commonly use the following technologies:

  • JWT (JSON Web Token): A compact token format commonly used to carry claims and securely communicate identity and authorization information.
  • OAuth 2.0: An authorization framework that allows applications to obtain limited access to protected resources.
  • OpenID Connect (OIDC): An identity layer built on top of OAuth 2.0 that provides authentication and user identity information.
  • ASP.NET Core Identity: A membership system that manages application users, passwords, roles, claims and related account functionality.

Understanding how these technologies work together is essential when building secure Web APIs, web applications, mobile applications and microservices.

2. Table of Contents

  1. Authentication vs Authorization
  2. What is JWT?
  3. JWT Structure
  4. How JWT Authentication Works
  5. Implement JWT Authentication in ASP.NET Core
  6. JWT Token Validation
  7. Claims-Based Authentication and Authorization
  8. Role-Based Authorization
  9. Policy-Based Authorization
  10. What is OAuth 2.0?
  11. OAuth 2.0 Grant Types
  12. What is OpenID Connect?
  13. OAuth 2.0 vs OpenID Connect
  14. ASP.NET Core Identity
  15. Identity Providers
  16. External Authentication and Social Login
  17. Access Tokens and Refresh Tokens
  18. Cookie Authentication vs JWT Authentication
  19. Authentication and Authorization Middleware
  20. Authentication in Microservices
  21. Security Best Practices
  22. Common Authentication and Authorization Mistakes
  23. Interview Questions
  24. Summary
  25. Conclusion

3. Authentication vs Authorization

What is authentication?

Authentication is the process of verifying the identity of a user or application.

It answers the question:

"Who are you?"

For example, when a user logs into an application using an email address and password, the application verifies the supplied credentials.

What is authorization?

Authorization determines whether an authenticated user or application has permission to perform a particular operation or access a resource.

It answers the question:

"What are you allowed to do?"

For example:

  • An Admin can create, update and delete employees.
  • A Manager can view and update employees in their department.
  • An Employee can view their own profile.

Authentication vs Authorization

Aspect Authentication Authorization
Purpose Verifies identity. Checks permissions.
Question Who are you? What can you access?
When Usually performed before authorization. Performed when accessing a protected resource.
Examples Password, JWT, cookies, OpenID Connect. Roles, claims, policies and permissions.
ASP.NET Core Authentication middleware. Authorization middleware.

Real-world example

Consider an employee management application.

  1. The user enters an email address and password.
  2. The application verifies the credentials. This is authentication.
  3. The application identifies the user's role as Manager.
  4. The user requests an employee management endpoint.
  5. The application checks whether the Manager role has permission to access that endpoint. This is authorization.

4. What is JWT?

JWT stands for JSON Web Token.

It is a compact, URL-safe token format used to represent claims between two parties. JWTs are commonly used as bearer access tokens in Web API authentication systems.

A JWT can contain information such as:

  • User ID.
  • Username.
  • Email address.
  • Roles.
  • Permissions or scopes.
  • Token expiration time.
  • Token issuer and intended audience.

Why use JWT?

  • It is compact and easy to transmit through HTTP headers.
  • It can be validated without querying the user database on every request.
  • It supports claims-based identity.
  • It is commonly used by Web APIs and distributed applications.
  • It supports signed tokens that can be verified by the receiving application.

Important: JWT is a token format, not an authentication protocol by itself. An application must define how tokens are issued, validated and used.

5. JWT Structure

A typical signed JWT consists of three parts separated by dots.

Header.Payload.Signature

Example of a JWT structure:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiIxMjMiLCJuYW1lIjoiSm9obiIsImV4cCI6MTk5OTk5OTk5OX0
.
signature-value

5.1 Header

The header identifies the token type and the signing algorithm.

{
  "alg": "HS256",
  "typ": "JWT"
}

Common signing algorithms include:

  • HS256: HMAC using SHA-256. The issuer and validator share a secret key.
  • RS256: RSA using SHA-256. The issuer signs using a private key, and validators use the corresponding public key.
  • ES256: ECDSA using the P-256 curve and SHA-256.

5.2 Payload

The payload contains claims, which represent information about the subject and token.

{
  "sub": "123",
  "name": "John",
  "email": "john@example.com",
  "role": "Admin",
  "iss": "https://identity.example.com",
  "aud": "employee-api",
  "exp": 1999999999
}

Common JWT claims include:

Claim Meaning
sub Subject, usually the user or application identifier.
iss Issuer that created the token.
aud Intended audience of the token.
exp Token expiration time.
iat Time at which the token was issued.
nbf Time before which the token must not be accepted.
jti Unique identifier of the token.

5.3 Signature

The signature helps the receiving application verify that the token has not been modified and was signed by an entity possessing the appropriate signing key.

For example, with an HMAC-based signing algorithm, the signature is calculated using the encoded header, encoded payload and a shared secret.

HMACSHA256(
    Base64UrlEncode(Header) + "." +
    Base64UrlEncode(Payload),
    SecretKey
)

Is JWT encrypted?

A typical signed JWT is not encrypted. Its header and payload are Base64URL-encoded, which is an encoding mechanism, not encryption.

Anyone who obtains a typical signed JWT can decode its payload. Therefore, do not store passwords, secret keys or other confidential information inside it.

JWT can also be encrypted using JSON Web Encryption (JWE), but signed JWTs are more commonly used for access-token scenarios.

6. How JWT Authentication Works

Consider an ASP.NET Core Web API that uses JWT bearer authentication.

Authentication flow

JWT Authentication Flow in ASP.NET Core Client App Web / Mobile 1. Login credentials Authentication API Identity Server 2. Verify credentials User Database 3. Valid user Token Issuer 4. Issue JWT access token Client App 5. API request + Bearer token ASP.NET Core API 6. Validate token Protected API Resource / Endpoint

Step-by-step explanation

  1. User login: The client sends login credentials to the authentication service over HTTPS.
  2. Credential validation: The authentication service verifies the credentials.
  3. Token creation: If the credentials are valid, the token issuer creates a signed access token.
  4. Token delivery: The client receives the access token.
  5. API request: The client sends the token in the Authorization header.
  6. Token validation: ASP.NET Core validates the token signature, issuer, audience and expiration.
  7. Authorization: ASP.NET Core checks whether the identity has permission to access the requested endpoint.
  8. Response: The API returns the requested resource or an appropriate HTTP error.

Example HTTP request

GET /api/employees HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...

The word Bearer indicates that the client is presenting a bearer token to access the protected resource.

7. Implement JWT Authentication in ASP.NET Core

The following example demonstrates a simplified JWT authentication implementation using ASP.NET Core Web API and a shared HMAC signing key.

For production systems, a dedicated identity provider with properly managed signing keys is generally preferable.

Step 1: Install the required package

Install the JWT bearer authentication package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Step 2: Configure JWT settings

For demonstration purposes, the configuration can contain the issuer, audience and signing key.

{
  "Jwt": {
    "Issuer": "https://identity.example.com",
    "Audience": "employee-api",
    "SecretKey": "ReplaceWithAProperlyManagedLongRandomSecret"
  }
}

Security note: This example illustrates configuration only. Do not commit production signing keys to source control or store them in ordinary application configuration files. Use a secure secret store or key-management system.

Step 3: Configure authentication middleware

In Program.cs, register JWT bearer authentication and authorization services.

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var jwtSettings = builder.Configuration
    .GetSection("Jwt");
var secretKey = jwtSettings["SecretKey"];
if (string.IsNullOrWhiteSpace(secretKey))
{
    throw new InvalidOperationException(
        "JWT signing key is not configured.");
}
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters =
            new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = jwtSettings["Issuer"],
                ValidateAudience = true,
                ValidAudience = jwtSettings["Audience"],
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(secretKey)),
                ValidateLifetime = true,
                ClockSkew = TimeSpan.FromMinutes(1)
            };
    });
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Step 4: Create a token generation service

A token issuer creates a signed token after the user has been successfully authenticated.

The following code illustrates the token creation mechanism. The caller must first validate the user's credentials through a proper user-management or identity service.

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
public class JwtTokenService
{
    private readonly IConfiguration _configuration;
    public JwtTokenService(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    public string GenerateToken(
        string userId,
        string email,
        string role)
    {
        var jwtSettings =
            _configuration.GetSection("Jwt");
        var key = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(
                jwtSettings["SecretKey"]!));
        var credentials = new SigningCredentials(
            key,
            SecurityAlgorithms.HmacSha256);
        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, userId),
            new Claim(ClaimTypes.Email, email),
            new Claim(ClaimTypes.Role, role)
        };
        var token = new JwtSecurityToken(
            issuer: jwtSettings["Issuer"],
            audience: jwtSettings["Audience"],
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(15),
            signingCredentials: credentials);
        return new JwtSecurityTokenHandler()
            .WriteToken(token);
    }
}

Step 5: Register the token service

builder.Services.AddScoped<JwtTokenService>();

Step 6: Protect an API endpoint

Use the Authorize attribute to require an authenticated identity.

[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public IActionResult GetEmployees()
    {
        return Ok("Authenticated user can access employees.");
    }
}

Step 7: Access the current user's claims

[HttpGet("profile")]
[Authorize]
public IActionResult GetProfile()
{
    var userId = User.FindFirst(
        ClaimTypes.NameIdentifier)?.Value;
    var email = User.FindFirst(
        ClaimTypes.Email)?.Value;
    return Ok(new
    {
        UserId = userId,
        Email = email
    });
}

The User property represents the ClaimsPrincipal created by the authentication middleware after successful authentication.

8. JWT Token Validation

When an API receives a JWT bearer token, it must validate the token before trusting its claims.

Important validation checks

Validation Purpose
Signature Verifies that the token was signed using a trusted signing key.
Issuer Verifies who issued the token.
Audience Verifies that the token is intended for this API.
Expiration Ensures the token has not expired.
Not Before Ensures the token is not being used before its valid starting time.

What happens if validation fails?

  • Invalid signature: The token is rejected.
  • Expired token: Authentication fails.
  • Incorrect issuer: The token is rejected.
  • Incorrect audience: The token is rejected.
  • Missing or invalid token: The request is treated as unauthenticated.

For an endpoint requiring authentication, an unauthenticated request generally receives HTTP 401 Unauthorized.

An authenticated user who does not have the required permission generally receives HTTP 403 Forbidden.

9. Claims-Based Authentication and Authorization

What are claims?

A claim is a statement about a user or application.

Examples include:

  • User ID.
  • Email address.
  • Department.
  • Role.
  • Permission.
  • Country.

Claims are represented using a claim type and a value.

Example claims

var claims = new List<Claim>
{
    new Claim(ClaimTypes.NameIdentifier, "1001"),
    new Claim(ClaimTypes.Name, "John"),
    new Claim(ClaimTypes.Email, "john@example.com"),
    new Claim(ClaimTypes.Role, "Manager"),
    new Claim("Department", "IT")
};

Access claims in a controller

[Authorize]
[HttpGet("my-details")]
public IActionResult GetMyDetails()
{
    var userId = User.FindFirst(
        ClaimTypes.NameIdentifier)?.Value;
    var department = User.FindFirst(
        "Department")?.Value;
    return Ok(new
    {
        UserId = userId,
        Department = department
    });
}

Claims-based authorization

ASP.NET Core allows authorization based on specific claims.

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ITDepartment", policy =>
        policy.RequireClaim("Department", "IT"));
});

Apply the policy to an endpoint:

[Authorize(Policy = "ITDepartment")]
[HttpGet("it-reports")]
public IActionResult GetITReports()
{
    return Ok("IT department reports.");
}

Only identities containing the required Department claim with the value IT can satisfy this policy.

10. Role-Based Authorization

What is role-based authorization?

Role-based authorization controls access based on the roles assigned to users.

Common roles include:

  • Admin.
  • Manager.
  • Employee.
  • Customer.
  • Support.

Example

[Authorize(Roles = "Admin")]
[HttpDelete("{id}")]
public IActionResult DeleteEmployee(int id)
{
    return Ok("Employee deleted.");
}

Only users with the Admin role can access this endpoint.

Allow multiple roles

[Authorize(Roles = "Admin,Manager")]
[HttpGet]
public IActionResult GetEmployees()
{
    return Ok("Employees list.");
}

In this example, the user must belong to at least one of the specified roles.

Different roles for different endpoints

[Authorize(Roles = "Admin")]
[HttpPost]
public IActionResult CreateEmployee()
{
    return Ok("Employee created.");
}
[Authorize(Roles = "Admin,Manager")]
[HttpPut("{id}")]
public IActionResult UpdateEmployee(int id)
{
    return Ok("Employee updated.");
}
[Authorize(Roles = "Employee")]
[HttpGet("my-profile")]
public IActionResult GetMyProfile()
{
    return Ok("Employee profile.");
}

Role-based vs Claims-based authorization

Role-based Claims-based
Uses roles to control access. Uses claims about the identity.
Suitable for broad access categories. Suitable for more detailed conditions.
Example: Admin. Example: Department = IT.
Example: [Authorize(Roles = "Admin")]. Example: RequireClaim("Department", "IT").

11. Policy-Based Authorization

What is policy-based authorization?

Policy-based authorization allows developers to define reusable authorization rules using requirements and handlers.

It is more flexible than simple role-based authorization because a policy can combine multiple conditions.

Step 1: Define a policy

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("MinimumAge",
        policy =>
            policy.RequireClaim("Age", "18", "19", "20"));
});

This example is only suitable for a simple demonstration. For a general age comparison, use a custom authorization requirement and handler rather than enumerating possible values.

Step 2: Apply the policy

[Authorize(Policy = "MinimumAge")]
[HttpGet("restricted")]
public IActionResult GetRestrictedData()
{
    return Ok("Access granted.");
}

Custom authorization requirement

Suppose only employees belonging to the IT department should access a particular resource.

Create a requirement:

using Microsoft.AspNetCore.Authorization;
public class DepartmentRequirement
    : IAuthorizationRequirement
{
    public string Department { get; }
    public DepartmentRequirement(string department)
    {
        Department = department;
    }
}

Create an authorization handler

using Microsoft.AspNetCore.Authorization;
public class DepartmentHandler
    : AuthorizationHandler<DepartmentRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        DepartmentRequirement requirement)
    {
        var department = context.User.FindFirst(
            "Department")?.Value;
        if (department == requirement.Department)
        {
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }
}

Register the handler and policy

builder.Services.AddSingleton<IAuthorizationHandler,
    DepartmentHandler>();
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ITOnly", policy =>
        policy.Requirements.Add(
            new DepartmentRequirement("IT")));
});

Apply the policy

[Authorize(Policy = "ITOnly")]
[HttpGet("department-data")]
public IActionResult GetDepartmentData()
{
    return Ok("IT department data.");
}

When should you use policy-based authorization?

  • When access depends on multiple conditions.
  • When authorization rules need to be reused.
  • When permissions depend on department or business rules.
  • When resource-specific authorization is required.
  • When simple role checks are not sufficient.

12. What is OAuth 2.0?

OAuth 2.0 is an authorization framework that allows an application to obtain limited access to protected resources on behalf of a user or as an application itself.

It is commonly used when one application needs to access resources hosted by another application without directly collecting or storing the user's password.

Real-world example

Suppose a calendar application wants permission to access a user's calendar from an external calendar service.

Instead of asking the user to provide their calendar-service password to the third-party application, OAuth 2.0 allows the user to grant specific access through the authorization server.

Important OAuth 2.0 components

Component Responsibility
Resource Owner The user who owns the protected resources.
Client The application requesting access.
Authorization Server Authenticates the resource owner when applicable and issues authorization tokens.
Resource Server Hosts protected resources and validates access tokens.

OAuth 2.0 flow

OAuth 2.0 Authorization Flow Client App 1. Authorization request Authorization Server 2. User grants permission Authorization Server 3. Access token Client App 4. API request with token Resource Server 5. Validate token and permissions Protected Data

Important point

OAuth 2.0 is primarily an authorization framework. It does not, by itself, define a standard way for the client to authenticate the user and obtain standardized identity information.

OpenID Connect provides that identity layer.

13. OAuth 2.0 Grant Types

OAuth 2.0 defines different ways for clients to obtain access tokens. The appropriate flow depends on the client type and security requirements.

13.1 Authorization Code Flow with PKCE

Authorization Code Flow with Proof Key for Code Exchange (PKCE) is the recommended approach for most interactive applications, including mobile applications, single-page applications and other public clients.

It is also commonly used by confidential web applications.

How it works

  1. The client creates a cryptographically random code verifier.
  2. The client derives a code challenge from the verifier.
  3. The client redirects the user to the authorization server.
  4. The user authenticates and grants permission.
  5. The authorization server redirects the client with an authorization code.
  6. The client exchanges the code and code verifier for tokens.
  7. The authorization server validates the code verifier and issues tokens.

PKCE helps protect the authorization code from being used by an unauthorized party if the code is intercepted.

13.2 Client Credentials Flow

Client Credentials Flow is used when an application needs to access a protected API using its own identity rather than acting on behalf of a user.

Example: A background service needs to access another internal API.

OAuth 2.0 Client Credentials Flow Background Service Client ID + Client Authentication Authorization Server Access Token Background Service Bearer Token Protected API

Client Credentials Flow does not involve an interactive user login.

13.3 Implicit Flow

Implicit Flow was historically used by browser-based applications to obtain access tokens directly through the browser redirect response.

It is no longer recommended for modern applications. Authorization Code Flow with PKCE is preferred.

13.4 Resource Owner Password Credentials Grant

This older grant type allowed an application to collect a user's username and password and exchange them directly for a token.

It is deprecated and should not be used for new applications. Modern applications should use authorization flows that redirect users to the authorization server.

OAuth 2.0 flow comparison

Flow Typical usage Recommendation
Authorization Code with PKCE Mobile apps, SPA and interactive web applications. Recommended.
Client Credentials Service-to-service communication. Recommended for machine-to-machine access.
Implicit Older browser applications. Do not use for new applications.
Password Grant Older applications collecting user passwords. Deprecated; do not use.

14. What is OpenID Connect?

OpenID Connect (OIDC) is an identity and authentication protocol built on top of OAuth 2.0.

OAuth 2.0 provides authorization, while OpenID Connect adds standardized authentication and user identity information.

OpenID Connect introduces an important token called the ID Token.

What is an ID Token?

An ID Token is a signed JWT that contains claims about the authenticated user and the authentication event.

Example:

{
  "iss": "https://identity.example.com",
  "sub": "user-1001",
  "aud": "web-client",
  "exp": 1999999999,
  "iat": 1999999000,
  "email": "john@example.com",
  "name": "John"
}

Important ID Token claims

Claim Meaning
iss Identity provider that issued the token.
sub Unique identifier of the authenticated subject.
aud Client application for which the ID Token was issued.
exp Token expiration time.
iat Time at which the token was issued.
nonce Value used to associate the authentication request with the returned ID Token and help prevent replay attacks.

What is the UserInfo endpoint?

OpenID Connect defines a UserInfo endpoint that can return additional claims about an authenticated user.

The client calls this endpoint using an appropriate access token.

OpenID Connect authentication flow

OpenID Connect Authorization Code Flow Client App 1. OpenID Connect authorization request Identity Provider 2. User authenticates Identity Provider 3. Authorization Code Client App 4. Exchange code for tokens Identity Provider 5. ID Token + Access Token Client App

When should you use OpenID Connect?

  • Single sign-on (SSO).
  • Enterprise application authentication.
  • Social login.
  • Mobile application login.
  • Centralized identity management.
  • Applications using external identity providers.

15. OAuth 2.0 vs OpenID Connect

Aspect OAuth 2.0 OpenID Connect
Purpose Authorization. Authentication and identity information.
Built on Authorization framework. OAuth 2.0.
Main token Access Token. ID Token, along with access tokens when resource access is needed.
Identifies the user Not standardized by OAuth 2.0 alone. Yes, through the ID Token and UserInfo endpoint.
Common use case Granting API access. User login and single sign-on.

Simple example

Suppose an application allows users to sign in using an external identity provider and then access an employee API.

  • OpenID Connect: Establishes the user's identity and authenticates the user.
  • OAuth 2.0: Allows the client to obtain permission to call the employee API.
  • Access Token: Is presented to the employee API.
  • ID Token: Provides identity information to the client application.

Important: An ID Token is intended for the client application. An API should validate an access token issued for that API rather than accepting an ID Token as an API access token.

16. ASP.NET Core Identity

What is ASP.NET Core Identity?

ASP.NET Core Identity is a membership system that provides functionality for managing application users and their authentication-related information.

It provides features such as:

  • User registration.
  • Password hashing and validation.
  • User login and logout.
  • Role management.
  • Claims management.
  • Password reset.
  • Email confirmation.
  • Two-factor authentication.
  • External login integration.

How does ASP.NET Core Identity work?

ASP.NET Core Identity Architecture ASP.NET Core App ASP.NET Core Identity UserManager SignInManager Identity Database Users / Roles Claims / Logins

Register Identity services

Example using Entity Framework Core as the Identity store:

builder.Services
    .AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

Register a user

public class AccountService
{
    private readonly UserManager<IdentityUser> _userManager;
    public AccountService(
        UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }
    public async Task<IdentityResult> RegisterUserAsync(
        string email,
        string password)
    {
        var user = new IdentityUser
        {
            UserName = email,
            Email = email
        };
        return await _userManager.CreateAsync(
            user,
            password);
    }
}

Verify user credentials

var user = await userManager.FindByEmailAsync(email);
if (user == null)
{
    return Unauthorized();
}
var result = await signInManager.CheckPasswordSignInAsync(
    user,
    password,
    lockoutOnFailure: true);
if (!result.Succeeded)
{
    return Unauthorized();
}

This example checks credentials using ASP.NET Core Identity. A complete login flow must also establish the appropriate application session or obtain tokens from an appropriate token issuer.

Identity vs JWT

ASP.NET Core Identity JWT
Manages users, passwords, roles and claims. Defines a token format.
Provides user-management APIs. Carries claims in a token.
Can use a database to store user information. Can be validated using cryptographic keys.
Does not automatically provide a complete OAuth 2.0 or OpenID Connect server. Does not automatically provide a complete login or identity system.

17. Identity Providers

What is an identity provider?

An Identity Provider (IdP) is a system responsible for authenticating users and issuing identity information or tokens to client applications.

It can provide authentication, single sign-on, token issuance, user management and integration with external identity systems.

Common identity providers

  • Microsoft Entra ID: Enterprise identity and access management, commonly used in Microsoft cloud environments.
  • Keycloak: Open-source identity and access management solution supporting OAuth 2.0 and OpenID Connect.
  • Auth0: Identity platform offering authentication and authorization services.
  • Okta: Identity and access management platform.
  • Duende IdentityServer: Identity and token service framework for .NET applications.

How an identity provider integrates with ASP.NET Core

External Identity Provider Authentication Flow Web / Mobile Client Login request Identity Provider Entra ID / Keycloak Access Token ASP.NET Core API Validate token Protected Resources

Why use an external identity provider?

  • Centralized authentication.
  • Single sign-on across applications.
  • Centralized user and access management.
  • Support for modern authentication standards.
  • Reduced need to build and maintain authentication infrastructure.

18. External Authentication and Social Login

What is external authentication?

External authentication allows users to sign in using an identity provider instead of creating and maintaining a separate password for every application.

Examples include:

  • Microsoft account.
  • Google account.
  • GitHub account.
  • Enterprise identity provider.

How does it work?

  1. The user selects an external login option.
  2. The application redirects the user to the identity provider.
  3. The identity provider authenticates the user.
  4. The identity provider returns an authentication response.
  5. The application validates the response.
  6. The application creates its own session or establishes an appropriate application identity.

ASP.NET Core external authentication configuration

For example, an application can configure an OpenID Connect-compatible external provider using an appropriate authentication package and provider settings.

builder.Services
    .AddAuthentication()
    .AddOpenIdConnect("ExternalProvider", options =>
    {
        options.Authority =
            "https://identity.example.com";
        options.ClientId =
            builder.Configuration["Authentication:ClientId"];
        options.ClientSecret =
            builder.Configuration["Authentication:ClientSecret"];
        options.ResponseType = "code";
        options.UsePkce = true;
        options.SaveTokens = false;
    });

This is a simplified configuration example. A real provider integration must also configure the correct callback path, scopes, token validation, client authentication method and other provider-specific settings.

19. Access Tokens and Refresh Tokens

What is an access token?

An access token is a credential presented by a client to access a protected resource.

Access tokens are usually short-lived to reduce the impact if a token is compromised.

What is a refresh token?

A refresh token is a credential that can be used with an authorization server to obtain a new access token, subject to the server's policies.

Access token vs Refresh token

Access Token Refresh Token
Used to access protected APIs. Used to obtain new access tokens.
Usually short-lived. Usually longer-lived.
Presented to the resource server. Presented to the authorization server.
Contains or represents authorization information. Allows token renewal according to authorization-server policy.

Refresh token flow

Refresh Token Flow Client Application 1. Access Token expires Authorization Server 2. Client submits Refresh Token Authorization Server 3. Validate Refresh Token Authorization Server 4. Issue new Access Token Client Application

Refresh token security

  • Store refresh tokens securely.
  • Use refresh token rotation where supported.
  • Revoke refresh tokens when users sign out or when compromise is suspected.
  • Apply expiration and inactivity policies.
  • Do not expose refresh tokens unnecessarily to browser scripts.

20. Cookie Authentication vs JWT Authentication

Cookie authentication

Cookie authentication stores an authentication ticket in a browser cookie. The browser automatically sends the cookie with matching requests.

ASP.NET Core commonly uses cookie authentication for traditional server-rendered web applications.

JWT bearer authentication

JWT bearer authentication uses an access token that the client explicitly presents in the Authorization header.

Comparison

Aspect Cookie Authentication JWT Bearer Authentication
Credential storage Browser cookie. Client-managed token storage.
Request transmission Browser automatically sends matching cookies. Client sends Authorization: Bearer token.
Common usage Traditional web applications. Web APIs and distributed clients.
CSRF considerations Requires appropriate CSRF protection. Depends on how the token is stored and transmitted.
Server-side session Can use a protected authentication ticket. Can validate signed tokens without a per-request session lookup.

Which should you choose?

  • Use cookie authentication for many traditional browser-based applications.
  • Use JWT bearer authentication when clients need to call protected APIs using access tokens.
  • For browser applications using OAuth or OpenID Connect, consider a Backend-for-Frontend (BFF) architecture to keep tokens on the server and use a secure browser session cookie.

Neither approach is automatically more secure in every situation. The correct choice depends on the application architecture and threat model.

21. Authentication and Authorization Middleware

What is middleware?

Middleware is software that forms part of the ASP.NET Core HTTP request pipeline. Each middleware component can process a request, call the next component and process the response.

Authentication and authorization are implemented through middleware in ASP.NET Core.

Correct middleware order

var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Why is the order important?

  • UseAuthentication(): Identifies the caller and establishes HttpContext.User.
  • UseAuthorization(): Checks whether the caller is allowed to access the requested resource.
  • MapControllers(): Maps controller endpoints into the request pipeline.

Authentication should normally execute before authorization because authorization depends on the identity established by authentication.

22. Authentication in Microservices

What is the challenge?

In a microservices architecture, multiple independent services may need to authenticate callers and enforce authorization rules.

For example:

  • User Service.
  • Order Service.
  • Payment Service.
  • Product Service.

Each service should protect its own resources instead of assuming that a request is trusted simply because it came from another internal service.

Recommended architecture

Secure ASP.NET Core Microservices Architecture Web / Mobile App 1. Authenticate Identity Provider Entra ID / Keycloak 2. Access Token (JWT) API Gateway Token Validation 3. Authorized Request 3. Authorized Request User Service ASP.NET Core API Order Service ASP.NET Core API User Database Database per Service Order Database Database per Service

How it works

  1. The user authenticates with the identity provider.
  2. The identity provider issues an access token.
  3. The client sends the token to the API gateway.
  4. The gateway validates the token and applies gateway-level policies.
  5. The gateway routes the request to the appropriate microservice.
  6. The target service validates the token or receives a securely established identity context according to the architecture.
  7. The service enforces its own authorization rules.

Important microservices security practices

  • Use a centralized identity provider.
  • Use appropriate token audiences and scopes for APIs.
  • Validate tokens at the resource services, not only at the gateway.
  • Use client credentials or another suitable workload identity mechanism for service-to-service communication.
  • Use TLS for service communication.
  • Avoid sharing signing secrets unnecessarily across services.
  • Apply least-privilege permissions.
  • Do not trust arbitrary identity headers from external clients.

23. Security Best Practices

1. Always use HTTPS

HTTPS protects credentials and tokens while they are transmitted between clients and servers.

2. Use short-lived access tokens

Short-lived access tokens reduce the time available for an attacker to misuse a compromised token.

3. Protect signing keys

Store signing keys in secure secret-management or key-management systems. Rotate keys according to an appropriate security policy.

4. Validate issuer and audience

Always validate the token issuer, audience, signature and lifetime. Never accept a token simply because it is correctly formatted.

5. Use PKCE for authorization code flows

Use Authorization Code Flow with PKCE for public clients such as mobile and browser-based applications.

6. Do not store sensitive information in JWT payloads

A typical signed JWT is readable by anyone who obtains it. Never include passwords, private keys or confidential information in its payload.

7. Protect browser-based token storage

Protect tokens from cross-site scripting and other browser attacks. Avoid storing long-lived sensitive credentials in browser-accessible storage without carefully assessing the risks.

8. Apply the principle of least privilege

Grant users and applications only the permissions required to perform their responsibilities.

9. Implement token revocation where necessary

JWT access tokens are often validated locally and may remain valid until expiration. Use short lifetimes, refresh-token revocation, key rotation or additional revocation mechanisms where the application requires faster invalidation.

10. Implement account protection

  • Use secure password hashing.
  • Support multi-factor authentication where appropriate.
  • Apply account lockout or other abuse protections.
  • Implement secure password-reset processes.
  • Monitor suspicious authentication activity.

24. Common Authentication and Authorization Mistakes

Mistake Why it is a problem Recommended approach
Confusing authentication with authorization A valid login does not automatically grant access to every resource. Implement separate authentication and authorization checks.
Not validating token audience A token intended for another resource may be accepted incorrectly. Validate the expected audience.
Using long-lived access tokens A compromised token may remain usable for too long. Use appropriate short lifetimes.
Storing secrets in source code Secrets can be exposed through repositories and deployments. Use secure secret management.
Using JWT without signature validation Untrusted token contents could be accepted. Validate the signature using trusted keys.
Using ID Tokens to access APIs ID Tokens are intended for the client, not as API access credentials. Validate an access token issued for the API.
Using the deprecated password grant It requires applications to handle user passwords directly. Use modern authorization flows.
Checking roles only at the UI Client-side controls can be bypassed. Enforce authorization on the server.
Accepting tokens at the gateway only Services may be exposed through other paths or internal callers. Protect resource services independently.
Ignoring CSRF and XSS Authentication credentials may be abused through browser attacks. Apply appropriate browser and session security controls.

25. Interview Questions

Q1. What is the difference between authentication and authorization?

Answer: Authentication verifies the identity of a user or application, while authorization determines what resources or operations that identity is permitted to access.

Q2. What is JWT?

Answer: JWT is a compact, URL-safe token format used to represent claims between parties. It is commonly used as a signed bearer access token for protecting Web APIs.

Q3. What are the three parts of a JWT?

Answer: Header, Payload and Signature.

Q4. Is JWT encrypted?

Answer: A typical signed JWT is not encrypted. Its payload is Base64URL-encoded and can be decoded. JWT can also be encrypted using JWE.

Q5. What is the difference between OAuth 2.0 and OpenID Connect?

Answer: OAuth 2.0 is an authorization framework used to grant access to protected resources. OpenID Connect builds on OAuth 2.0 and adds standardized user authentication and identity information.

Q6. What is the difference between an Access Token and an ID Token?

Answer: An Access Token is presented to a resource server to access protected resources. An ID Token provides identity information to the client application after authentication.

Q7. What is a Refresh Token?

Answer: A Refresh Token is a credential used to obtain a new access token from an authorization server without requiring the user to repeat the complete interactive authentication process, subject to the server's policies.

Q8. What is the N+1 problem in authentication-related API development?

Answer: Although N+1 is primarily a data-access issue, it can occur when retrieving user roles or permissions through repeated database queries. It can be reduced through efficient querying, projection and appropriate data loading.

Q9. What is claims-based authorization?

Answer: Claims-based authorization checks claims associated with an authenticated identity, such as department, country, permission or subscription type.

Q10. What is role-based authorization?

Answer: Role-based authorization controls access based on roles such as Admin, Manager and Employee. ASP.NET Core supports it through the Authorize attribute.

Q11. What is policy-based authorization?

Answer: Policy-based authorization uses reusable policies containing requirements and handlers to evaluate access rules. It supports more complex authorization conditions than simple role checks.

Q12. What is ASP.NET Core Identity?

Answer: ASP.NET Core Identity is a membership system that manages users, passwords, roles, claims, external logins, password recovery and other account-related functionality.

Q13. What is an Identity Provider?

Answer: An Identity Provider authenticates users and provides identity information or tokens to applications. Examples include Microsoft Entra ID, Keycloak and Okta.

Q14. What is PKCE?

Answer: Proof Key for Code Exchange is an extension to the OAuth 2.0 Authorization Code Flow that helps protect authorization codes from interception and misuse.

Q15. What is Client Credentials Flow?

Answer: Client Credentials Flow allows a confidential client application to obtain an access token using its own identity. It is commonly used for service-to-service communication.

Q16. What is the difference between HTTP 401 and HTTP 403?

Answer: HTTP 401 means the request lacks valid authentication credentials. HTTP 403 means the caller is authenticated but does not have permission to access the requested resource.

Q17. Why should issuer and audience be validated?

Answer: Issuer validation ensures the token came from a trusted authority. Audience validation ensures the token was intended for the receiving API or client.

Q18. What is Single Sign-On?

Answer: Single Sign-On (SSO) allows a user to authenticate through a centralized identity provider and access multiple applications without independently signing in to each application.

Q19. Why is JWT commonly used in microservices?

Answer: JWT access tokens can carry claims and be validated by multiple services using trusted signing keys or public-key metadata. This supports distributed API authentication without requiring every service to query the user database for each request.

Q20. What is the difference between Cookie Authentication and JWT Authentication?

Answer: Cookie authentication uses browser cookies to maintain an authenticated session. JWT bearer authentication uses an access token explicitly presented in the Authorization header. The appropriate approach depends on the client and application architecture.

26. Summary

Technology Purpose Typical usage
Authentication Verifies identity. User login and application identity.
Authorization Controls access. Roles, claims and policies.
JWT Token format. Bearer tokens and claims representation.
OAuth 2.0 Authorization framework. API access delegation.
OpenID Connect Authentication and identity layer. Login and single sign-on.
ASP.NET Core Identity User and account management. Registration, passwords, roles and claims.
Identity Provider Centralized identity and token services. Enterprise authentication and SSO.

27. Conclusion

Authentication and authorization are essential components of secure ASP.NET Core applications.

Understanding the differences between JWT, OAuth 2.0 and OpenID Connect helps developers choose the right approach for Web APIs, browser applications, mobile applications and microservices.

In practical ASP.NET Core development:

  • Use ASP.NET Core Identity when you need application user and account management.
  • Use JWT bearer authentication when an API needs to validate access tokens.
  • Use OAuth 2.0 when applications need delegated or application-level access to protected resources.
  • Use OpenID Connect when applications need standardized user authentication and identity information.
  • Use role-based, claims-based and policy-based authorization to enforce access rules.
  • Use a trusted identity provider when centralized authentication and single sign-on are required.

A secure production application should combine trusted identity management, correct token validation, server-side authorization, secure credential storage and continuous security monitoring.

Authentication and authorization are two distinct security processes used to protect systems and data.

Authentication (AuthN)

Authentication verifies identityโ€”ensuring that a user or system is who they claim to be.

Key Methods

  • Username & Password: Traditional login credentials.
  • Multi-Factor Authentication (MFA): Combines multiple factors (e.g., password + OTP).
  • Biometric Authentication: Uses fingerprints, facial recognition, or retina scans.
  • OAuth & OpenID Connect: Secure protocols for web authentication.

Authorization (AuthZ)

Authorization determines the actions a user can perform after authentication.

Key Methods

  • Role-Based Access Control (RBAC): Grants permissions based on user roles.
  • Attribute-Based Access Control (ABAC): Access based on attributes like location or device.
  • OAuth 2.0: Uses access tokens for secure API authorization.
  • JSON Web Tokens (JWT): Enables stateless authorization in web applications.

OAuth Architecture

  • Authorization Server: Authenticates users and issues access tokens.
  • Resource Server: Hosts protected resources.
  • Client: Requests access to protected resources.
  • Flows: Supports Authorization Code, Implicit, Client Credentials, and other flows.

JWT Architecture

  • Token Structure: Consists of a header, payload, and signature (Base64url encoded).
  • Header: Metadata including signing algorithm.
  • Payload: Contains claims (subject, issuer, audience).
  • Signature: Ensures token integrity and authenticity.
  • Verification: Performed using a public key (RSA) or secret key (HMAC).

API Keys Architecture

  • Key Distribution: Service providers issue API keys to clients.
  • Key Usage: Included in requests via headers or URL parameters.
  • Server-Side Validation: Keys are validated by the service provider.

Key Differences

  • Delegation: OAuth enables user access delegation to third-party apps.
  • Information Exchange: JWTs facilitate secure data transfer between parties.
  • Authentication: API keys authenticate clients simply.
  • Security: OAuth and JWTs offer stronger security than API keys.
  • Revocation: JWTs can be revoked for better access control.
  • User Context: OAuth and JWTs support user-specific permissions.

When to Use

  • OAuth: For third-party access without revealing credentials.
  • JWT: For secure info exchange and stateless authentication.
  • API Keys: For simple, internal applications needing basic authentication.

๐Ÿ” Types of Authentication in ASP.NET Core Web API

1. No Authentication

No authentication means the API is open to everyone. This is suitable for public endpoints like health checks or documentation, but not recommended for sensitive data.

2. Basic Authentication

The client sends a Base64-encoded username:password in the Authorization header. The server decodes and validates the credentials.

Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l
  

Note: Not secure unless used over HTTPS.

3. JWT Authentication

JSON Web Tokens (JWT) are compact tokens containing claims. The server issues a token after login, and the client includes it in the Authorization header.

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
  

JWTs are stateless and digitally signed, making them ideal for scalable APIs.

4. OAuth2 & OpenID Connect (OIDC)

OAuth2 is a protocol for delegated access. OIDC extends OAuth2 to include identity information. Commonly used with identity providers like Google, Azure AD, or IdentityServer.

  • Authorization Server: Issues tokens
  • Resource Server: Hosts protected APIs
  • Client: Requests access on behalf of user

Supports flows like Authorization Code, Client Credentials, and Implicit.

5. API Key Authentication

Clients include a unique API key in the request header or query string. The server validates the key to authenticate the client.

GET /api/data?apikey=12345
  

Simple to implement, but less secure than token-based methods.

6. Certificate Authentication

Uses client-side SSL certificates to authenticate users or devices. The server verifies the certificate during the TLS handshake.

Common in enterprise environments and IoT scenarios.

7. Windows Authentication

Uses the operating systemโ€™s credentials (e.g., Active Directory) to authenticate users. Supported via IIS or Kestrel with NTLM or Kerberos.

Ideal for intranet applications where users are part of a Windows domain.

โœ… Summary

  • No Authentication: Open access
  • Basic: Simple but insecure
  • JWT: Stateless and scalable
  • OAuth2/OIDC: Delegated and identity-aware
  • API Key: Lightweight client auth
  • Certificate: Secure device/user auth
  • Windows: Domain-based auth

Production grade Authentication Methods in ASP.NET Core Web API

In production-grade ASP.NET Core Web API applications, the most commonly used authentication methods are:

๐Ÿ” 1. JWT (JSON Web Token) Authentication

Why it's popular:

  • Stateless and scalable
  • Works well with REST APIs and microservices
  • Easy to integrate with front-end frameworks (React, Angular, etc.)

Use case:

Mobile apps, SPAs, distributed systems

๐ŸŒ 2. OAuth2 with OpenID Connect (OIDC)

Why it's popular:

  • Industry-standard for delegated access and identity federation
  • Supports third-party login (Google, Azure AD, etc.)
  • Secure and flexible

Use case:

Enterprise apps, multi-tenant SaaS platforms, external integrations

๐Ÿ”‘ 3. API Key Authentication

Why it's used:

  • Simple to implement
  • Good for internal services or server-to-server communication

Use case:

Internal APIs, microservices, IoT devices

๐Ÿงพ Honorable Mentions

  • Windows Authentication: Common in intranet and enterprise environments using Active Directory.
  • Certificate Authentication: Used in high-security or device-level authentication scenarios.
  • Basic Authentication: Rarely used in production due to security limitations (unless over HTTPS and with additional safeguards).

โœ… Summary

Authentication Type Common in Production Best For
JWT โœ… Yes REST APIs, SPAs
OAuth2 + OIDC โœ… Yes Enterprise, third-party login
API Key โœ… Yes Internal APIs, microservices
Windows Authentication โ˜‘๏ธ Sometimes Intranet, enterprise apps
Certificate โ˜‘๏ธ Niche Secure device-to-server comms
Basic Authentication โŒ Rare Legacy or simple internal tools
No Authentication โŒ Never Public endpoints only
๐Ÿ”™
SQL-and-NoSQL-database :👈 👉:Versioning in REST APIs