Database-Transaction-Management :👈 👉:Custom-Authorization-Policies

ASP.NET Core Authentication with Microsoft Entra ID and External Identity Providers

ASP.NET Core Authentication with Microsoft Entra ID and External Identity Providers

1. Introduction

Authentication is the process of verifying the identity of a user or application. In ASP.NET Core, authentication determines who is accessing an application, while authorization determines what that authenticated user is allowed to do.

Instead of implementing username and password management entirely inside an application, organizations often use external identity providers such as:

  • Microsoft Entra ID (formerly Azure Active Directory).
  • Microsoft Entra External ID.
  • Google.
  • Facebook.
  • GitHub.
  • Other OpenID Connect or OAuth 2.0 identity providers.
  • Enterprise identity systems supporting SAML 2.0.

ASP.NET Core supports integrating with these providers through authentication middleware and standard identity protocols.

2. Authentication vs Authorization

Authentication Authorization
Verifies who the user is. Determines what the user can access.
Uses credentials, tokens or identity provider responses. Uses roles, claims and policies.
Example: User signs in using Microsoft. Example: Only administrators can access an administration API.
Usually establishes an authenticated identity. Checks permissions for a requested resource.

3. Important Authentication Protocols

3.1 OAuth 2.0

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

For example, an application may obtain an access token to call Microsoft Graph.

OAuth 2.0 primarily deals with delegated or application authorization. By itself, it is not an authentication protocol.

3.2 OpenID Connect (OIDC)

OpenID Connect is an identity layer built on top of OAuth 2.0. It enables applications to authenticate users.

OIDC introduces the ID token, which contains claims about the authenticated user.

It is commonly used for ASP.NET Core web applications that redirect users to Microsoft Entra ID or another identity provider for sign-in.

3.3 SAML 2.0

SAML 2.0 is an XML-based authentication and federation standard commonly used in enterprise single sign-on environments.

It allows an application to trust an identity provider that authenticates users and sends signed SAML assertions.

SAML is still used in many enterprise systems, although OIDC is common for modern application integrations.

Protocol Comparison

Protocol Main Purpose Common Usage
OAuth 2.0 Authorization API access and delegated permissions
OpenID Connect Authentication and identity User login and SSO
SAML 2.0 Federated authentication Enterprise SSO

4. What Is Microsoft Entra ID?

Microsoft Entra ID is Microsoft's cloud-based identity and access management service. Its former name was Azure Active Directory (Azure AD).

It provides identity and access management capabilities for:

  • Employees and organizational users.
  • Enterprise applications.
  • APIs and backend services.
  • Single sign-on (SSO).
  • Multi-factor authentication (MFA).
  • Conditional Access.
  • Application permissions and delegated permissions.
  • Identity federation with external identity providers.

Example

Suppose an organization has an ASP.NET Core application used by employees.

Instead of creating separate passwords for every employee in the application, users can sign in using their organization's Microsoft accounts.

Microsoft Entra ID verifies the user and sends an authentication response to the application.

5. Important Microsoft Entra ID Terminology

Term Meaning
Tenant A dedicated Microsoft Entra ID directory representing an organization or identity environment.
Tenant ID A unique identifier for the tenant.
Application Registration A registration that defines how an application integrates with Microsoft Entra ID.
Client ID The unique application identifier assigned during registration.
Client Secret A credential used by a confidential client application to authenticate itself.
Redirect URI The URL to which the identity provider sends the authentication response.
Scope A requested permission or access scope.
ID Token A token containing identity claims about the authenticated user.
Access Token A token used to access a protected API.
Refresh Token A credential used by supported flows to obtain new access tokens without requiring a new interactive login.
Authority The identity provider endpoint used by the application for authentication and token operations.
Issuer The identity provider that issued a token.

6. Microsoft Entra ID Authentication Architecture

The following diagram shows how an ASP.NET Core web application authenticates a user through Microsoft Entra ID using OpenID Connect.

User / Browser Requests application ASP.NET Core Web Application Microsoft Entra ID Identity Provider 1. Request 2. Redirect to sign-in 3. User authenticates and receives authorization response 4. Callback Token Validation OIDC Middleware Authenticated Session Authentication Cookie 5. Access application

Authentication Steps

  1. The user opens the ASP.NET Core application.
  2. The application determines that the user is not authenticated.
  3. The application redirects the browser to Microsoft Entra ID.
  4. The user signs in and completes any required MFA or Conditional Access checks.
  5. Microsoft Entra ID sends an authorization response to the registered redirect URI.
  6. The application validates the response and establishes an authenticated session.
  7. The browser sends the authentication cookie on subsequent requests.

For a server-rendered web application, the OIDC middleware normally establishes a local authentication session using a cookie. The ID token is used to establish identity; it is not normally sent to the application's APIs as an access token.

7. Register an Application in Microsoft Entra ID

Before integrating ASP.NET Core with Microsoft Entra ID, register the application.

Step 1: Open Microsoft Entra Admin Center

Open:

Microsoft Entra Admin Center

Sign in using an account with the necessary permissions.

Step 2: Open App Registrations

  1. Navigate to Identity.
  2. Open Applications.
  3. Select App registrations.
  4. Select New registration.

Step 3: Register the Application

Provide the following information:

Field Example
Name MyAspNetCoreApplication
Supported Account Types Accounts in this organizational directory only, for a single-tenant application.
Redirect URI Platform Web
Redirect URI https://localhost:7001/signin-oidc

The redirect URI must match the application's actual configured callback URL, including scheme, host, port and path.

Step 4: Save Application Details

After registration, note these values:

  • Application (client) ID.
  • Directory (tenant) ID.

These values are required for application configuration.

Step 5: Create a Client Secret

  1. Open Certificates & secrets.
  2. Select Client secrets.
  3. Select New client secret.
  4. Provide a description and expiration period.
  5. Copy the secret value immediately and store it securely.

Security note: A client secret is a credential, not an ordinary application setting. Never commit it to source control, expose it in browser code, or place it in frontend JavaScript.

For production applications, prefer certificates or workload identity federation where appropriate. Store credentials securely, rotate them and restrict their access.

8. Configure ASP.NET Core Authentication with Microsoft Entra ID

For an ASP.NET Core web application, Microsoft provides the Microsoft Identity Web library to simplify integration with Microsoft Entra ID.

Step 1: Install NuGet Packages

dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.UI

The first package provides Microsoft Entra authentication integration. The UI package provides optional account-related UI components for supported ASP.NET Core web application templates.

Step 2: Configure appsettings.json

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "YOUR_TENANT_ID",
    "ClientId": "YOUR_CLIENT_ID",
    "CallbackPath": "/signin-oidc"
  }
}

Do not put a production client secret directly into a committed configuration file. Configure it using a secret store or secure deployment configuration.

Step 3: Configure Program.cs

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services
    .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(
        builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.Run();

Explanation

  • AddAuthentication() configures the authentication scheme.
  • AddMicrosoftIdentityWebApp() configures Microsoft Entra ID integration.
  • AddAuthorization() registers authorization services.
  • UseAuthentication() identifies the user and establishes the authenticated principal.
  • UseAuthorization() checks whether the user is allowed to access the requested resource.

Important: Authentication middleware must execute before authorization middleware.

Step 4: Protect a Controller

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize]
public class DashboardController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

The [Authorize] attribute requires the user to be authenticated before accessing the controller.

Step 5: Allow Anonymous Access

[AllowAnonymous]
public IActionResult PublicPage()
{
    return View();
}

[AllowAnonymous] allows access without authentication, even when a controller or a broader route group requires authentication.

9. Reading User Information and Claims

After authentication, ASP.NET Core exposes the authenticated user's identity through HttpContext.User.

A claims-based identity contains information such as:

  • User identifier.
  • Display name.
  • Email address, if supplied.
  • Tenant identifier.
  • Role or group information, if configured and included.

Read Claims in a Controller

using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize]
public class ProfileController : Controller
{
    public IActionResult Index()
    {
        var userId = User.FindFirstValue(
            ClaimTypes.NameIdentifier);
        var name = User.Identity?.Name;
        var email = User.FindFirstValue(
            ClaimTypes.Email);
        return Ok(new
        {
            UserId = userId,
            Name = name,
            Email = email
        });
    }
}

Claim names are not guaranteed to be identical across providers. Inspect the actual claims issued by your identity provider and map them deliberately.

10. Authorization Using Roles

Authentication confirms the user's identity. Roles can be used to determine which application functions the user can access.

Example

[Authorize(Roles = "Admin")]
public IActionResult AdminDashboard()
{
    return View();
}

Only users whose authenticated principal contains the required role can access this action.

For Microsoft Entra ID, application roles are commonly defined in the app registration or enterprise application configuration and assigned to users or groups.

Multiple Roles

[Authorize(Roles = "Admin,Manager")]
public IActionResult Reports()
{
    return View();
}

This allows a user with either the Admin or Manager role.

11. Authorization Using Policies

Policy-based authorization is more flexible than relying only on roles.

Configure a Policy

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("RequireEmployee", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim(
            "employeeType",
            "Employee");
    });
});

Apply the Policy

[Authorize(Policy = "RequireEmployee")]
public IActionResult EmployeeDashboard()
{
    return View();
}

Policies can check claims, roles, custom requirements and other authorization conditions.

12. What Is Single Sign-On (SSO)?

Single Sign-On allows users to authenticate once with an identity provider and access multiple applications without repeatedly entering their credentials, subject to session, policy and authentication requirements.

SSO Architecture

Microsoft Entra ID ASP.NET Core App A HR Portal ASP.NET Core App B Finance Portal ASP.NET Core App C Admin Portal One identity provider can serve multiple registered applications

Each application still validates its own authentication response and maintains its own local session. SSO does not mean that one application's authentication cookie automatically authenticates users in another application.

13. Authentication with Multiple Identity Providers

An ASP.NET Core application can support more than one external identity provider.

For example:

  • Employees sign in using Microsoft Entra ID.
  • Customers sign in using Google.
  • Partners sign in using another organization's identity provider.

Each provider has its own configuration, protocol and callback requirements.

Multiple Identity Provider Architecture

ASP.NET Core Application Microsoft Entra ID Google External OIDC Provider Application Identity Claims and Permissions

The application should normalize provider-specific claims into a consistent internal user model. It should also keep provider identities separate from the application's internal user identifier.

14. Integrating Google Authentication

ASP.NET Core supports external authentication using OAuth-based providers. Google supports OpenID Connect, and its authentication integration can be configured using the Google authentication handler.

Step 1: Create Google OAuth Credentials

Open:

Google Cloud Console

  1. Create or select a Google Cloud project.
  2. Configure the OAuth consent screen.
  3. Create an OAuth client ID.
  4. Select the Web application client type.
  5. Register the authorized redirect URI.

For the standard ASP.NET Core Google authentication handler, the callback path is commonly:

https://localhost:7001/signin-google

Use the exact callback URI configured in the application and registered with Google.

Step 2: Install the Package

dotnet add package Microsoft.AspNetCore.Authentication.Google

Step 3: Configure Google Authentication

builder.Services
    .AddAuthentication()
    .AddGoogle(options =>
    {
        options.ClientId =
            builder.Configuration["Authentication:Google:ClientId"]!;
        options.ClientSecret =
            builder.Configuration["Authentication:Google:ClientSecret"]!;
    });

Configure the Google client ID and secret through a secure configuration source. Do not commit real credentials to source control.

15. Configuring Multiple Authentication Schemes

When an application supports multiple providers, each authentication handler needs its own scheme name.

For example, the application may use:

  • Cookies for the local application session.
  • OpenID Connect for Microsoft Entra ID.
  • Google authentication for Google sign-in.

For a traditional server-rendered web application, a common pattern is to use cookies as the default authentication scheme and use external providers as challenge schemes.

Example Configuration

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services
    .AddAuthentication(options =>
    {
        options.DefaultScheme =
            CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme =
            OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddMicrosoftIdentityWebApp(
        builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.Run();

This configuration demonstrates a Microsoft Entra ID web sign-in flow with a local cookie session. Google authentication can be added as another external scheme when required.

Important: Avoid blindly combining multiple AddAuthentication() configurations. The default scheme, sign-in scheme, challenge scheme and callback paths must be configured deliberately. A multi-provider application also needs explicit login and challenge logic to choose the intended provider.

16. External Login Using Google and Microsoft Entra ID

A common login page allows users to select their identity provider.

For example:

<h2>Sign In</h2>
<a href="/Account/LoginMicrosoft">
    Sign in with Microsoft
</a>
<a href="/Account/LoginGoogle">
    Sign in with Google
</a>

The controller can initiate the appropriate challenge.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
public class AccountController : Controller
{
    public IActionResult LoginMicrosoft()
    {
        var properties = new AuthenticationProperties
        {
            RedirectUri = "/"
        };
        return Challenge(
            properties,
            "OpenIdConnect");
    }
    public IActionResult LoginGoogle()
    {
        var properties = new AuthenticationProperties
        {
            RedirectUri = "/"
        };
        return Challenge(
            properties,
            "Google");
    }
}

This example assumes that the application has registered schemes named OpenIdConnect and Google. The actual scheme names must match the configured handlers.

17. Authentication in ASP.NET Core Web APIs

Web APIs commonly authenticate requests using bearer access tokens.

Unlike a traditional web application that maintains a cookie-based session, a bearer-token API validates the access token included in the HTTP request.

API Authentication Flow

Client Application Web / Mobile Microsoft Entra ID Issues Access Token ASP.NET Core API Protected Resource Client obtains an access token for the API Authorization: Bearer access_token Token Validation Signature, issuer, audience, expiry Authorized API Response

Install Microsoft Identity Web API Package

dotnet add package Microsoft.Identity.Web

Configure appsettings.json

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "YOUR_TENANT_ID",
    "ClientId": "YOUR_API_APPLICATION_CLIENT_ID"
  }
}

Configure Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(
        builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Protect the API

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class OrdersController : ControllerBase
{
    [HttpGet]
    public IActionResult GetOrders()
    {
        return Ok(new
        {
            Message = "Authenticated API access successful"
        });
    }
}

When a request does not contain a valid access token, the API normally returns HTTP 401 Unauthorized.

18. ID Token vs Access Token

These two tokens have different purposes and should not be used interchangeably.

Feature ID Token Access Token
Purpose Provides information about the authenticated user. Grants access to a protected resource.
Used by OIDC client application. Target API or resource server.
Contains Identity claims. Authorization-related claims and scopes or roles.
Should be sent to an API as its bearer credential? No. Yes, when intended for that API.

Important: An API should validate that an access token's audience identifies that API. It must not accept an ID token as a substitute for an API access token.

19. JWT Access Token Structure

A JWT commonly consists of three Base64URL-encoded sections separated by dots.

HEADER.PAYLOAD.SIGNATURE

Header

Contains token metadata such as the signing algorithm and key identifier.

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "key-identifier"
}

Payload

Contains claims about the token.

{
  "iss": "https://login.microsoftonline.com/tenant-id/v2.0",
  "aud": "api-application-id",
  "sub": "user-subject-id",
  "exp": 1900000000,
  "scp": "orders.read"
}

Signature

The signature allows the resource server to verify that the token was issued by a trusted authority and has not been modified.

Security note: JWT payloads are encoded, not encrypted by default. Never put passwords, secrets or sensitive personal information into ordinary JWT claims.

20. Protecting APIs with Scopes

In Microsoft Entra ID, an API can expose delegated permissions called scopes.

For example:

  • orders.read: Read orders.
  • orders.write: Create or update orders.
  • products.read: Read product information.

The API validates the token and checks whether the required scope is present.

Example Scope Policy

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("OrdersRead", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireAssertion(context =>
        {
            var scope = context.User.FindFirst("scp")?.Value;
            return scope?
                .Split(' ', StringSplitOptions.RemoveEmptyEntries)
                .Contains("orders.read") == true;
        });
    });
});

Apply the Policy

[Authorize(Policy = "OrdersRead")]
[HttpGet]
public IActionResult GetOrders()
{
    return Ok();
}

For application-only access, use application permissions and the appropriate app-role authorization checks rather than treating delegated scopes and application roles as interchangeable.

21. Delegated Permissions vs Application Permissions

Delegated Permissions Application Permissions
Application accesses a resource on behalf of a signed-in user. Application accesses a resource using its own identity.
Used in user sign-in scenarios. Used in background services and daemon applications.
Token commonly contains an scp claim. Token commonly contains a roles claim for app roles.
Example: User reads their own calendar. Example: A background service processes organization-wide data.

22. Client Credentials Flow

The client credentials flow is used when an application needs to access an API without a signed-in user.

For example, a scheduled background service needs to call another protected API.

Flow

Background Service Confidential Client Microsoft Entra ID Token Endpoint Protected API Resource Server 1. Authenticate 2. Token 3. API response No interactive user sign-in Application identity and permissions

The client authenticates using a certificate, client secret or supported workload identity mechanism. Microsoft Entra ID issues an access token for the target API if the application is authorized.

In production, certificates or workload identity federation are often preferable to long-lived client secrets where supported.

23. Using Microsoft Identity Web to Call Another API

Microsoft Identity Web can acquire access tokens for downstream APIs.

For a web application calling Microsoft Graph or another protected API, the application can use token acquisition services.

Register Token Acquisition Services

builder.Services
    .AddMicrosoftIdentityWebApp(
        builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

In production, choose an appropriate token cache implementation for your application's scale, hosting model and security requirements. In-memory caches are not shared across application instances and do not survive restarts.

Example Service Using an Access Token

using Microsoft.Identity.Web;
public class GraphService
{
    private readonly ITokenAcquisition _tokenAcquisition;
    private readonly HttpClient _httpClient;
    public GraphService(
        ITokenAcquisition tokenAcquisition,
        HttpClient httpClient)
    {
        _tokenAcquisition = tokenAcquisition;
        _httpClient = httpClient;
    }
    public async Task<string> GetProfileAsync()
    {
        var accessToken =
            await _tokenAcquisition.GetAccessTokenForUserAsync(
                new[] { "User.Read" });
        using var request = new HttpRequestMessage(
            HttpMethod.Get,
            "https://graph.microsoft.com/v1.0/me");
        request.Headers.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue(
                "Bearer",
                accessToken);
        var response = await _httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

The example assumes the required Microsoft Graph delegated permission has been configured and consented to, and that the user has an appropriate authenticated session.

24. What Is Microsoft Entra External ID?

Microsoft Entra External ID is Microsoft's customer and external identity solution. It supports authentication experiences for customers and other external users.

It is useful when an organization wants customers to sign in using supported identity options without managing all customer passwords itself.

External ID can support scenarios such as:

  • Customer registration and sign-in.
  • Social identity provider integration.
  • Self-service account management.
  • Customer identity lifecycle management.
  • Identity federation.

Important distinction: Microsoft Entra ID workforce tenants are primarily designed for organizational identities. Microsoft Entra External ID supports external customer identity scenarios. Choose the appropriate tenant and configuration based on whether the users are employees, partners or customers.

25. What Is Microsoft Entra B2B?

Microsoft Entra B2B collaboration allows an organization to invite external users, such as suppliers, consultants or business partners, to access organizational resources.

Example:

  • Company A uses Microsoft Entra ID.
  • Company B has its own identity provider.
  • Company A invites an employee from Company B.
  • The external employee authenticates using an accepted identity method.
  • Company A controls access to its resources.

B2B collaboration is different from building a public customer registration and login system.

26. External Identity Provider vs Microsoft Entra ID

Feature Microsoft Entra ID External Identity Provider
Identity management Managed through Microsoft Entra ID. Managed by the external provider.
Authentication Microsoft-managed authentication. Provider-specific authentication.
Integration Microsoft Identity Web or OIDC middleware. OIDC, OAuth-based handlers or other supported protocols.
Common use Employees and enterprise applications. Customers, social login and partner identities.
Authorization Roles, groups, scopes and claims. Application-defined roles, policies and claims mapping.

27. Authentication Cookie vs JWT Bearer Token

Authentication Cookie JWT Bearer Token
Commonly used for server-rendered web applications. Commonly used for APIs and service-to-service calls.
Browser sends the cookie automatically according to cookie rules. Client typically sends the token in the Authorization header.
Session can be represented by an encrypted and signed authentication ticket. Token contains claims and is validated by the resource server.
Requires appropriate CSRF protection for cookie-authenticated state-changing requests. Bearer tokens in Authorization headers are not normally automatically attached by browsers, but XSS and token theft remain important risks.

A common architecture uses OIDC to authenticate a user and a secure cookie to maintain the web application's local session. The application separately obtains access tokens when it needs to call protected APIs.

28. Multi-Factor Authentication (MFA)

Multi-Factor Authentication requires users to verify their identity using more than one authentication factor.

Common factors include:

  • Something the user knows, such as a password.
  • Something the user has, such as an authenticator app or security key.
  • Something the user is, such as a biometric verification supported by the device.

Microsoft Entra ID can enforce MFA through authentication methods and Conditional Access policies.

In most enterprise applications, MFA is configured and enforced at the identity provider level rather than manually implemented in every ASP.NET Core application.

29. Conditional Access

Conditional Access allows an organization to control access based on conditions such as:

  • User or group membership.
  • Application being accessed.
  • Device compliance.
  • Sign-in risk.
  • Location or network conditions.
  • Authentication strength.

For example, an organization may require MFA when employees access an application from an untrusted device.

Conditional Access policies are evaluated by Microsoft Entra ID. ASP.NET Core applications should not attempt to replace these identity-provider security controls with simple client-side checks.

30. Logout from Microsoft Entra ID

For an application using Microsoft Identity Web and the OIDC web sign-in flow, logout can be initiated through the authentication system.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;
public class AccountController : Controller
{
    public IActionResult Logout()
    {
        return SignOut(
            new AuthenticationProperties
            {
                RedirectUri = "/"
            },
            CookieAuthenticationDefaults.AuthenticationScheme,
            OpenIdConnectDefaults.AuthenticationScheme);
    }
}

This signs out of the local cookie session and initiates the configured OIDC sign-out flow. Exact sign-out behavior depends on provider configuration and the provider's browser session.

31. Common Authentication Security Risks

Risk Explanation Protection
Token Theft An attacker obtains an access token. Protect token storage, use TLS and avoid exposing tokens to browser scripts.
Weak Client Secret Management Secrets are exposed in source code or configuration files. Use Key Vault or another secure secret store.
Invalid Token Audience An API accepts a token intended for another resource. Validate the audience claim.
Invalid Issuer A token comes from an untrusted authority. Validate the issuer and tenant requirements.
Expired Tokens A token is used beyond its validity period. Validate token lifetime and use supported renewal flows.
Open Redirect Authentication redirects users to untrusted destinations. Validate return URLs and allow only safe local destinations.
CSRF A browser sends an unwanted authenticated request. Use anti-forgery protection for cookie-authenticated state-changing operations.
Incorrect Claim Mapping Application trusts an incorrect or inconsistent claim. Validate trusted claims and map identities deliberately.
Excessive Permissions Applications receive more access than required. Apply least privilege and review permissions regularly.

32. Best Practices

  • Use OpenID Connect for modern user authentication.
  • Use OAuth 2.0 access tokens for protected API access.
  • Use Microsoft Identity Web for Microsoft Entra ID integration in ASP.NET Core.
  • Always use HTTPS in production.
  • Validate token signature, issuer, audience and lifetime.
  • Use authorization policies instead of scattering permission checks throughout controllers.
  • Apply the principle of least privilege to scopes and application permissions.
  • Use MFA and Conditional Access where appropriate.
  • Never expose client secrets or access tokens in frontend code.
  • Use certificates or workload identity federation for confidential clients where appropriate.
  • Store secrets in Azure Key Vault or another secure secret manager.
  • Use secure, HTTP-only and appropriately configured cookies.
  • Protect cookie-authenticated state-changing requests against CSRF.
  • Use stable provider identifiers rather than email addresses as the primary external identity key.
  • Validate external provider claims before linking accounts.
  • Do not automatically link accounts solely because two providers return the same email address.
  • Use a secure token cache for downstream API access.
  • Log authentication failures without logging passwords, secrets or complete tokens.
  • Keep authentication libraries updated.

33. Common Mistakes to Avoid

  • Using an ID token to call an API instead of an access token.
  • Confusing OAuth 2.0 with OpenID Connect.
  • Forgetting to register the correct redirect URI.
  • Using the wrong tenant ID or client ID.
  • Placing a client secret in frontend JavaScript.
  • Using authentication without authorization checks.
  • Trusting email addresses as permanent user identifiers.
  • Assuming that every external identity provider returns identical claims.
  • Accepting tokens without validating their audience.
  • Using a wildcard redirect URL without validation.
  • Storing access tokens in browser local storage without considering the risks.
  • Assuming that logging out of an application automatically terminates every identity provider session.
  • Using the same authentication configuration for MVC applications and bearer-token APIs without understanding their different requirements.

34. Real-World Enterprise Architecture

Consider an enterprise application containing an employee portal, customer portal, API gateway and multiple microservices.

Identity Providers Entra ID / External ID / Google Employee Portal ASP.NET Core MVC Customer Portal ASP.NET Core Mobile Application Native / Flutter API Gateway Token validation / routing Order Service Protected API Payment Service Protected API Inventory Service Protected API Each API validates tokens intended for its own resource

Architecture Explanation

  1. Employees authenticate through the organization's Microsoft Entra ID tenant.
  2. Customers authenticate through the configured customer identity system.
  3. Web applications establish their own secure local sessions.
  4. Clients obtain access tokens for protected APIs.
  5. The API gateway validates tokens according to its responsibilities and routes requests.
  6. Each backend API also enforces its own authentication and authorization requirements.
  7. Services use scopes, application roles and business permissions to control access.

Important: An API gateway should not be the only security boundary. Backend services must validate the tokens or receive identity through a separately secured, trusted architecture.

35. Interview Questions and Answers

Q1. What is Microsoft Entra ID?

Microsoft Entra ID is Microsoft's cloud identity and access management service. It provides authentication, authorization, SSO, MFA and identity management capabilities.

Q2. What was the previous name of Microsoft Entra ID?

Its previous name was Azure Active Directory (Azure AD).

Q3. What is OpenID Connect?

OpenID Connect is an identity layer built on OAuth 2.0 that allows applications to authenticate users using ID tokens.

Q4. What is the difference between OAuth 2.0 and OIDC?

OAuth 2.0 is an authorization framework used to obtain access to resources. OIDC adds authentication and identity information through ID tokens.

Q5. What is a tenant in Microsoft Entra ID?

A tenant is a dedicated identity directory that represents an organization or identity environment.

Q6. What is an application registration?

It defines an application's identity and configuration in Microsoft Entra ID, including client ID, redirect URIs and permissions.

Q7. What is a client ID?

It is the unique identifier assigned to an application during registration.

Q8. What is a client secret?

It is a credential used by a confidential client to authenticate itself to the identity provider. It must be stored securely.

Q9. What is a redirect URI?

It is the registered application URL to which the identity provider sends the authentication response.

Q10. What is an ID token?

An ID token is an OIDC token containing claims about the authenticated user. It is intended for the OIDC client application.

Q11. What is an access token?

An access token is a credential used to access a protected API or resource.

Q12. What is SSO?

Single Sign-On allows users to authenticate with an identity provider and access multiple registered applications without repeatedly entering credentials, subject to session and policy requirements.

Q13. What is Microsoft Identity Web?

It is a Microsoft library that simplifies integrating ASP.NET Core applications and APIs with Microsoft Entra ID.

Q14. What is a claims-based identity?

It represents an authenticated user using claims such as user identifier, name, email, tenant and permissions.

Q15. What is the difference between a role and a claim?

A claim is a statement about a subject. A role is a type of claim commonly used to represent an assigned responsibility or access category.

Q16. What is MFA?

Multi-Factor Authentication requires users to verify their identity using more than one authentication factor.

Q17. What is Conditional Access?

Conditional Access allows organizations to apply access policies based on conditions such as user, device, location and risk.

Q18. What is the client credentials flow?

It is an OAuth 2.0 flow where an application authenticates using its own identity rather than a signed-in user's identity.

Q19. What is delegated permission?

It allows an application to access a resource on behalf of a signed-in user.

Q20. What is application permission?

It allows an application to access a resource using its own identity without a signed-in user.

Q21. How do you secure an ASP.NET Core Web API using Microsoft Entra ID?

Register the API, configure its audience and scopes or app roles, integrate Microsoft Identity Web or JWT bearer authentication, and apply authorization policies.

Q22. What is the difference between Microsoft Entra ID and Microsoft Entra External ID?

Microsoft Entra ID workforce tenants primarily support organizational identities. Microsoft Entra External ID provides capabilities for external customer identity scenarios.

Q23. What is B2B collaboration?

It allows organizations to provide external users, such as business partners and suppliers, access to selected organizational resources.

Q24. Can an ASP.NET Core application support Google and Microsoft authentication together?

Yes. Each provider can be configured as a separate authentication scheme. The application must manage provider selection, callbacks and claims mapping correctly.

Q25. Why should an API not accept an ID token?

An ID token is intended for the client application. An API must validate an access token intended for that API, including its audience and other security properties.

36. Final Summary

  • Authentication verifies a user's identity, while authorization determines what that user can access.
  • Microsoft Entra ID provides enterprise identity and access management.
  • OpenID Connect is commonly used for user authentication.
  • OAuth 2.0 is commonly used for API authorization.
  • Microsoft Identity Web simplifies Microsoft Entra ID integration with ASP.NET Core.
  • Application registration defines the application identity and redirect URIs.
  • ID tokens identify users to OIDC clients; access tokens authorize access to APIs.
  • Claims, roles and policies help implement authorization.
  • External identity providers can be integrated using separate authentication schemes.
  • Microsoft Entra External ID supports customer identity scenarios.
  • Use secure credential storage, least privilege, MFA and proper token validation.

37. Official Microsoft Documentation

🔙
Database-Transaction-Management :👈 👉:Custom-Authorization-Policies