Introduction

If you develop web applications, APIs or distributed systems, you have already faced the need to answer two fundamental questions: “who are you?” (authentication) and “what can you do?” (authorization). These two concepts are the pillars of any secure system, but they often cause confusion — especially when protocols such as OAuth2, OpenID Connect and tokens such as JWT come into play.

In this article, I will demystify these concepts in a practical and didactic way. You will understand the difference between authentication and authorization, how JWT (JSON Web Token) works under the hood, the role of OAuth 2.0 in access delegation, and how OpenID Connect adds the missing identity layer. In addition, I will explore the Client ID types that exist in Azure Entra ID (formerly Azure AD) and when to use each one for SPA, Server-Side and REST API applications.

This content is aimed at back-end, front-end and full-stack developers who want to implement authentication and authorization correctly and securely. If you work with automation and system integration, this article will also be useful — just as understanding the differences between terminal and pipeline matters for execution contexts, the security of your flows depends on understanding how identities are managed. And if you already master these fundamentals and want to take your SPA’s security to the next level, check out BFF Backend For Frontend: Security in SPAs, where I apply these concepts in the BFF pattern. If you are looking for an open-source and free solution to implement all of this on your own infrastructure, see Keycloak: Free Authentication with Containers and C#.

📦 Source code: The full implementation of this article is in the blog-zocateli-sample repository on GitHub. See the examples in C# / Entra ID, Angular / MSAL and Python / Flask.


Authentication vs. Authorization: What Is the Difference?

Before diving into the protocols, it is essential to understand the difference between these two concepts which, although related, have completely different responsibilities.

Authentication (AuthN) is the process of verifying the identity of a user or system. It is the answer to the question: “Are you who you say you are?”. When you type your email and password on a login screen, you are going through an authentication process. Other examples include biometrics, digital certificates and access tokens.

Authorization (AuthZ) is the process of verifying permissions. After confirming who you are, the system needs to decide: “What are you allowed to do?”. An authenticated user may have access to certain resources, but not all of them. For example, a developer may be allowed to read production logs, but not to delete databases.

AspectAuthentication (AuthN)Authorization (AuthZ)
Question“Who are you?”“What can you do?”
WhenHappens firstHappens after authentication
MechanismLogin, passwords, tokens, biometricsRoles, claims, policies, scopes
ProtocolOpenID Connect, SAMLOAuth 2.0
ExampleLogging in with email and passwordAccessing the API’s /admin endpoint

ℹ️ Info: A very common mistake is treating OAuth 2.0 as an authentication protocol. In fact, OAuth 2.0 is an authorization protocol. The authentication layer is added by OpenID Connect, which is built on top of OAuth 2.0.


What Is JWT (JSON Web Token)?

JWT (pronounced “jot”) is an open standard defined in RFC 7519 for transmitting information compactly and securely between parties as a JSON object. It is widely used as the token format in authentication and authorization flows.

Structure of a JWT

A JWT is made up of three parts separated by dots (.):

1
xxxxx.yyyyy.zzzzz
  1. Header — contains the token type and the signing algorithm.
  2. Payload — contains the claims (statements) about the entity and metadata.
  3. Signature — guarantees that the token has not been tampered with.

Decoded JWT Example

Header:

1
2
3
4
5
{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "abc123"
}

Payload:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "iss": "https://login.microsoftonline.com/{tenant-id}/v2.0",
  "sub": "user-object-id",
  "aud": "api://minha-api-client-id",
  "exp": 1739750400,
  "iat": 1739746800,
  "name": "Lincoln Zocateli",
  "preferred_username": "[email protected]",
  "roles": ["Admin", "Reader"],
  "scp": "User.Read Profile.Read"
}

Important Claims in the Azure Entra ID Context

ClaimDescription
issToken issuer — identifies Azure Entra ID
subSubject — unique user identifier
audAudience — the application/API the token was issued for
expToken expiration (Unix timestamp)
iatMoment of issuance (issued at)
rolesRoles assigned to the user in the application
scpDelegated scopes — granted permissions
tidAzure Entra Tenant ID
oidUser Object ID in the directory

⚠️ Warning: Never store sensitive information in a JWT payload. The payload is Base64-encoded, but not encrypted — anyone can decode it. The signature only guarantees integrity, not confidentiality. If you need confidentiality, use JWE (JSON Web Encryption) as described in RFC 7516.

Validating a JWT

When receiving a JWT, your application MUST validate:

  1. Signature — verify it with the issuer’s public key (available at the JWKS endpoint).
  2. Issuer (iss) — confirm the issuer is the expected one.
  3. Audience (aud) — confirm the token was issued for your API.
  4. Expiration (exp) — reject expired tokens.
  5. Not Before (nbf) — if present, reject tokens before the allowed time.

OAuth 2.0: The Authorization Protocol

OAuth 2.0 is an authorization framework defined in RFC 6749 that allows applications to obtain limited access to a user’s resources on a server without exposing the user’s credentials to the application.

The Four OAuth 2.0 Roles

The protocol defines four fundamental roles:

  1. Resource Owner — the user who owns the data (e.g., the account owner).
  2. Client — the application that wants to access the data on behalf of the user.
  3. Authorization Server — the server that authenticates the user and issues tokens (e.g., Azure Entra ID).
  4. Resource Server — the API that protects the resources and validates the tokens.

Main Flows (Grant Types)

OAuth 2.0 defines several flows for different scenarios. Each type of application uses the flow best suited to its architecture:

FlowScenarioSecurity
Authorization Code + PKCESPAs, mobile apps, web appsHigh
Client CredentialsServer-to-server communication (M2M)High
On-Behalf-Of (OBO)APIs calling other APIs on behalf of the userHigh
Device CodeDevices without a browser (IoT, CLI)Medium
ImplicitSPAs (OBSOLETE — do not use)Low
Resource Owner Password (ROPC)Direct login with password (OBSOLETE)Low

⚠️ Warning: The Implicit and Resource Owner Password Credentials (ROPC) flows are considered obsolete and insecure. The IETF recommendation and Microsoft’s guidance is to use Authorization Code with PKCE for all public applications (SPAs and mobile).

The Authorization Code Flow with PKCE

This is the recommended flow for most modern applications. Here is the step by step:

  1. The Client generates a code_verifier (random string) and a code_challenge (SHA-256 hash of the verifier).
  2. The Client redirects the user to the Authorization Server with the code_challenge.
  3. The user authenticates and consents to the access.
  4. The Authorization Server returns an authorization code to the Client.
  5. The Client exchanges the authorization code + code_verifier for an access token.
  6. The Client uses the access token to access the Resource Server (API).
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
┌──────────┐                              ┌───────────────────┐
│  Client   │──(1) Auth Request + PKCE ──►│ Authorization     │
│  (App)    │                              │ Server            │
│           │◄─(4) Authorization Code ─────│ (Azure Entra ID)  │
│           │──(5) Code + Verifier ───────►│                   │
│           │◄─(6) Access Token ──────────│                   │
│           │                              └───────────────────┘
│           │──(7) API Request + Token ──►┌───────────────────┐
│           │◄─(8) Protected Resource ────│ Resource Server   │
└──────────┘                              │ (Your API)        │
                                          └───────────────────┘

OpenID Connect: Identity on Top of OAuth 2.0

OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0. While OAuth 2.0 answers “what can you access?”, OIDC answers “who are you?”.

OIDC introduces a new type of token: the ID Token. This token is a JWT that contains information about the authenticated user (name, email, picture, etc.) and is issued together with the access token.

Difference Between the Tokens

TokenPurposeFormatWho consumes it?
ID TokenUser identity informationJWTThe Client (front-end)
Access TokenAuthorization to access protected resourcesJWT*The Resource Server
Refresh TokenObtain new access tokens without re-authenticatingOpaqueThe Authorization Server

ℹ️ Info: The Access Token issued by Azure Entra ID is a JWT, but the OAuth 2.0 specification does not mandate that format — some providers use opaque tokens. Always validate the token according to your provider’s documentation.

OpenID Connect Scopes

OIDC defines standardized scopes that determine which user information is returned:

  • openid — required to enable the OIDC flow; returns the sub claim.
  • profile — returns name, family_name, given_name, picture, etc.
  • email — returns email and email_verified.
  • offline_access — requests a refresh token for access renewal.

SAML 2.0: The Corporate Identity Protocol

Before moving on to the Client ID types in Azure Entra, it is worth knowing another protocol widely used in corporate environments: SAML 2.0 (Security Assertion Markup Language). While OpenID Connect dominates the landscape of modern applications (SPAs, REST APIs, mobile), SAML remains the standard in many organizations — especially for integration with legacy systems, ERPs and federation between companies.

What Is SAML 2.0?

SAML 2.0 is an open XML-based standard, defined by OASIS, for exchanging authentication and authorization data between an Identity Provider (IdP) and a Service Provider (SP). It was published in 2005 and became the dominant protocol for corporate Single Sign-On (SSO) over the last decade.

How Does the SAML Flow Work?

The most common flow is SP-Initiated SSO (login starts at the service the user wants to access):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
┌──────────┐                              ┌───────────────────┐
│   User    │──(1) Accesses service ──────►│ Service Provider  │
│ (Browser) │                              │ (Your App)        │
│           │◄─(2) Redirect to IdP ────────│                   │
│           │──(3) Login at IdP ──────────►┌───────────────────┐
│           │                              │ Identity Provider │
│           │◄─(4) SAML Response (XML) ────│ (Azure AD, ADFS,  │
│           │──(5) POST to SP ────────────►│  Keycloak, etc.)  │
│           │◄─(6) Session established ────└───────────────────┘
└──────────┘                              │ Service Provider  │
                                          └───────────────────┘
  1. The user accesses the Service Provider (your application)
  2. The SP detects that the user is not authenticated and generates a SAML AuthnRequest (XML)
  3. The browser is redirected to the Identity Provider with the AuthnRequest
  4. The user authenticates at the IdP (login, MFA, etc.)
  5. The IdP generates a SAML Response containing an Assertion (signed statement with the user’s data)
  6. The browser POSTs the SAML Response to the SP, which validates the signature and establishes the session

SAML Assertion: The Structure

A SAML Assertion is a digitally signed XML document that contains:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
                ID="_abc123" IssueInstant="2025-12-15T10:00:00Z">
  <saml:Issuer>https://idp.empresa.com</saml:Issuer>
  <saml:Subject>
    <saml:NameID>[email protected]</saml:NameID>
  </saml:Subject>
  <saml:Conditions NotBefore="2025-12-15T10:00:00Z"
                   NotOnOrAfter="2025-12-15T11:00:00Z">
    <saml:AudienceRestriction>
      <saml:Audience>https://app.seudominio.com</saml:Audience>
    </saml:AudienceRestriction>
  </saml:Conditions>
  <saml:AttributeStatement>
    <saml:Attribute Name="email">
      <saml:AttributeValue>[email protected]</saml:AttributeValue>
    </saml:Attribute>
    <saml:Attribute Name="role">
      <saml:AttributeValue>Admin</saml:AttributeValue>
    </saml:Attribute>
  </saml:AttributeStatement>
</saml:Assertion>

ℹ️ Info: Unlike JWT (which is compact and JSON-based), the SAML Assertion is XML-based — more verbose, but with a consolidated and widely audited digital signature model (XML Signature).

SAML 2.0 vs OpenID Connect: When to Use Each?

AspectSAML 2.0OpenID Connect
FormatXMLJSON (JWT)
TransportHTTP Redirect / POSTHTTP Redirect / REST
Token sizeLarge (verbose XML)Compact (JWT)
Ideal scenariosCorporate SSO, B2B federation, legacySPAs, REST APIs, mobile, microservices
Mobile supportWeak (heavy XML)Native (JSON + PKCE)
MaturitySince 2005, very widespread in enterpriseSince 2014, standard for modern apps
Identity ProvidersADFS, Shibboleth, PingFederate, KeycloakAzure Entra, Google, Keycloak, Auth0
Base protocolIndependentBuilt on OAuth 2.0

💡 Tip: In practice, many modern identity providers support both protocols. Keycloak, for example, is an open-source IdP that implements OAuth 2.0, OpenID Connect and SAML 2.0 — allowing you to serve both modern applications and legacy systems with a single identity server.

Practical recommendation:

  • For new applications (SPAs, APIs, mobile): use OpenID Connect
  • For integration with legacy corporate systems (SAP, Salesforce, ADFS): use SAML 2.0
  • For mixed environments: use an IdP that supports both (Azure Entra ID, Keycloak) and configure each application with the most suitable protocol

Client ID Types in Azure Entra ID

In Azure Entra ID, when you register an application, you get a Client ID (also called Application ID). However, the registration type and the platform configuration vary according to the nature of the application. This directly affects the OAuth flow used and the security level.

Public vs. Confidential Application

Azure Entra ID classifies applications into two fundamental types:

TypeCan keep a secret?ExamplesRecommended flows
PublicNoSPA, mobile, desktop, CLIAuthorization Code + PKCE
ConfidentialYesServer-side web app, daemon, APIAuth Code + Secret, Client Credentials

💡 Tip: An application is public when it runs in an environment the user controls (browser, phone, desktop) — where a secret cannot be stored securely. An application is confidential when it runs on a server you control.

1. Client ID for SPA Applications (Single Page Application)

A SPA (Single Page Application) is a front-end application that runs entirely in the browser, such as React, Angular or Vue.js applications. Because the code runs on the client side, it is not possible to store Client Secrets — any secret would be exposed in the source code or in the browser’s developer tools.

Configuration in Azure Entra ID:

  • Platform type: Single-page application
  • Application type: Public client
  • Redirect URI: http://localhost:4200 (dev) / https://app.seudominio.com (production)
  • OAuth flow: Authorization Code with PKCE
  • Client Secret: DO NOT use — public applications must not have a secret

Registration via Azure CLI:

1
2
3
4
5
6
7
8
9
# Register a SPA application in Azure Entra ID
az ad app create \
  --display-name "My Angular SPA" \
  --sign-in-audience "AzureADMyOrg" \
  --enable-id-token-issuance true \
  --enable-access-token-issuance false \
  --web-redirect-uris "" \
  --public-client-redirect-uris "http://localhost:4200" \
  --is-fallback-public-client true

Example with Angular 16+ and @azure/msal-angular:

First, install the required dependencies:

1
npm install @azure/msal-browser @azure/msal-angular

MSAL configuration (auth-config.ts):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// src/app/auth-config.ts — MSAL configuration for Angular 16+
import { MsalGuardConfiguration, MsalInterceptorConfiguration } from "@azure/msal-angular";
import {
  BrowserCacheLocation,
  InteractionType,
  IPublicClientApplication,
  LogLevel,
  PublicClientApplication,
} from "@azure/msal-browser";

// MSAL configuration — does NOT include a client secret (public app)
export function MSALInstanceFactory(): IPublicClientApplication {
  return new PublicClientApplication({
    auth: {
      clientId: "seu-client-id-aqui",             // Application (client) ID
      authority: "https://login.microsoftonline.com/seu-tenant-id",
      redirectUri: "http://localhost:4200",         // Redirect URI configured in the portal
      postLogoutRedirectUri: "http://localhost:4200",
    },
    cache: {
      cacheLocation: BrowserCacheLocation.SessionStorage, // sessionStorage for SPAs
      storeAuthStateInCookie: false,
    },
    system: {
      loggerOptions: {
        logLevel: LogLevel.Info,
        loggerCallback: (level, message) => console.log(message),
      },
    },
  });
}

// MsalGuard configuration — protects routes that require authentication
export function MSALGuardConfigFactory(): MsalGuardConfiguration {
  return {
    interactionType: InteractionType.Redirect, // Redirect or Popup
    authRequest: {
      scopes: ["openid", "profile", "email"],
    },
  };
}

// MsalInterceptor configuration — automatically injects the access token into HTTP requests
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
  const protectedResources = new Map<string, Array<string>>();
  // Every request to your API will receive the token automatically
  protectedResources.set("https://api.seudominio.com/*", ["api://minha-api/User.Read"]);
  // Microsoft Graph (optional)
  protectedResources.set("https://graph.microsoft.com/v1.0/*", ["User.Read"]);

  return {
    interactionType: InteractionType.Redirect,
    protectedResourceMap: protectedResources,
  };
}

Main module with the standalone API (app.config.ts):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// src/app/app.config.ts — Angular 16+ standalone configuration
import { ApplicationConfig, importProvidersFrom } from "@angular/core";
import { provideRouter } from "@angular/router";
import { provideHttpClient, withInterceptorsFromDi, HTTP_INTERCEPTORS } from "@angular/common/http";
import {
  MsalModule,
  MsalService,
  MsalGuard,
  MsalInterceptor,
  MsalBroadcastService,
  MSAL_INSTANCE,
  MSAL_GUARD_CONFIG,
  MSAL_INTERCEPTOR_CONFIG,
} from "@azure/msal-angular";
import {
  MSALInstanceFactory,
  MSALGuardConfigFactory,
  MSALInterceptorConfigFactory,
} from "./auth-config";
import { routes } from "./app.routes";

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(withInterceptorsFromDi()),
    importProvidersFrom(MsalModule),
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor, // Interceptor injects the token into requests automatically
      multi: true,
    },
    {
      provide: MSAL_INSTANCE,
      useFactory: MSALInstanceFactory,
    },
    {
      provide: MSAL_GUARD_CONFIG,
      useFactory: MSALGuardConfigFactory,
    },
    {
      provide: MSAL_INTERCEPTOR_CONFIG,
      useFactory: MSALInterceptorConfigFactory,
    },
    MsalService,
    MsalGuard,             // Guard to protect routes
    MsalBroadcastService,  // Service to observe authentication events
  ],
};

Protected routes (app.routes.ts):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// src/app/app.routes.ts — Routes with MsalGuard to protect access
import { Routes } from "@angular/router";
import { MsalGuard } from "@azure/msal-angular";
import { HomeComponent } from "./home/home.component";
import { DashboardComponent } from "./dashboard/dashboard.component";

export const routes: Routes = [
  { path: "", component: HomeComponent },
  {
    path: "dashboard",
    component: DashboardComponent,
    canActivate: [MsalGuard], // Protected route — requires authentication
  },
];

Component with login and API call (home.component.ts):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// src/app/home/home.component.ts — Component with login and API consumption
import { Component, OnInit, OnDestroy, inject } from "@angular/core";
import { CommonModule } from "@angular/common";
import { HttpClient } from "@angular/common/http";
import { MsalService, MsalBroadcastService } from "@azure/msal-angular";
import { InteractionStatus } from "@azure/msal-browser";
import { Subject, filter, takeUntil } from "rxjs";

@Component({
  selector: "app-home",
  standalone: true,
  imports: [CommonModule],
  template: `
    <div *ngIf="!isAutenticado">
      <h2>Welcome</h2>
      <button (click)="login()">Login with Azure Entra ID</button>
    </div>
    <div *ngIf="isAutenticado">
      <h2>Hello, {{ nomeUsuario }}!</h2>
      <button (click)="chamarApi()">Call Protected API</button>
      <button (click)="logout()">Logout</button>
      <pre *ngIf="dadosApi">{{ dadosApi | json }}</pre>
    </div>
  `,
})
export class HomeComponent implements OnInit, OnDestroy {
  private msalService = inject(MsalService);
  private broadcastService = inject(MsalBroadcastService);
  private http = inject(HttpClient);
  private destroy$ = new Subject<void>();

  isAutenticado = false;
  nomeUsuario = "";
  dadosApi: any = null;

  ngOnInit(): void {
    // Observe changes in the authentication state
    this.broadcastService.inProgress$
      .pipe(
        filter((status) => status === InteractionStatus.None),
        takeUntil(this.destroy$)
      )
      .subscribe(() => {
        const accounts = this.msalService.instance.getAllAccounts();
        this.isAutenticado = accounts.length > 0;
        if (this.isAutenticado) {
          this.nomeUsuario = accounts[0].name ?? accounts[0].username;
        }
      });
  }

  login(): void {
    // Starts the login flow via redirect (Authorization Code + PKCE)
    this.msalService.loginRedirect({
      scopes: ["openid", "profile", "email", "api://minha-api/User.Read"],
    });
  }

  logout(): void {
    this.msalService.logoutRedirect({
      postLogoutRedirectUri: "http://localhost:4200",
    });
  }

  chamarApi(): void {
    // MsalInterceptor injects the access token automatically
    this.http.get("https://api.seudominio.com/api/dados").subscribe({
      next: (data) => (this.dadosApi = data),
      error: (err) => console.error("Error calling API:", err),
    });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

💡 Tip: In Angular 16+, MsalInterceptor automatically injects the access token into all HTTP requests that match the patterns configured in protectedResourceMap. You do not need to manage tokens manually — just use HttpClient normally.

ℹ️ Info: Although MSAL works well for SPAs, the most secure approach today is the BFF (Backend For Frontend) pattern, which avoids exposing tokens in the browser. See the full implementation in BFF Backend For Frontend: Security in SPAs.

2. Client ID for Server-Side Applications (Web App)

Server-side applications are traditional web applications that run on the server (e.g., ASP.NET, Django, Express.js). Because the code runs in a controlled environment, these applications can store a Client Secret securely.

Configuration in Azure Entra ID:

  • Platform type: Web
  • Application type: Confidential client
  • Redirect URI: https://app.seudominio.com/auth/callback
  • OAuth flow: Authorization Code (with Client Secret)
  • Client Secret: Yes — stored securely on the server (e.g., environment variable, Key Vault)

Registration via Azure CLI:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Register a confidential web application
az ad app create \
  --display-name "My Web App" \
  --sign-in-audience "AzureADMyOrg" \
  --web-redirect-uris "https://app.seudominio.com/auth/callback" \
  --enable-id-token-issuance true

# Create a Client Secret (valid for 2 years)
az ad app credential reset \
  --id "seu-app-object-id" \
  --display-name "Prod Secret" \
  --years 2

Example with Python (Flask + MSAL):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# app.py — Flask application with authentication via Azure Entra ID
import os
from flask import Flask, redirect, url_for, session, request
import msal

app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "dev-secret-key")

# Configuration — Client Secret stored in an environment variable
CLIENT_ID = os.environ["AZURE_CLIENT_ID"]
CLIENT_SECRET = os.environ["AZURE_CLIENT_SECRET"]  # Safe on the server
AUTHORITY = f"https://login.microsoftonline.com/{os.environ['AZURE_TENANT_ID']}"
REDIRECT_URI = "https://app.seudominio.com/auth/callback"
SCOPE = ["User.Read"]  # Microsoft Graph scopes

# Create a confidential MSAL instance
def criar_msal_app():
    return msal.ConfidentialClientApplication(
        CLIENT_ID,
        authority=AUTHORITY,
        client_credential=CLIENT_SECRET,  # Secret used here (secure server)
    )

@app.route("/login")
def login():
    """Starts the OAuth 2.0 Authorization Code authentication flow."""
    msal_app = criar_msal_app()
    # Generate the authorization URL
    auth_url = msal_app.get_authorization_request_url(
        scopes=SCOPE,
        redirect_uri=REDIRECT_URI,
    )
    return redirect(auth_url)

@app.route("/auth/callback")
def callback():
    """Azure Entra ID callback after authentication."""
    msal_app = criar_msal_app()
    code = request.args.get("code")

    # Exchange the authorization code for tokens
    result = msal_app.acquire_token_by_authorization_code(
        code,
        scopes=SCOPE,
        redirect_uri=REDIRECT_URI,
    )

    if "access_token" in result:
        session["user"] = result.get("id_token_claims")
        session["access_token"] = result["access_token"]
        return redirect(url_for("index"))
    else:
        return f"Authentication error: {result.get('error_description')}", 401

@app.route("/")
def index():
    """Main page — requires authentication."""
    user = session.get("user")
    if not user:
        return redirect(url_for("login"))
    return f"Hello, {user.get('name')}! You are authenticated."

if __name__ == "__main__":
    app.run(debug=True, port=5000)

⚠️ Warning: Never expose the Client Secret in source code, Git repositories or logs. Use environment variables, Azure Key Vault or secret management tools. In the example above, the values come from os.environ for security.

3. Client ID for REST APIs (Machine-to-Machine Communication)

When a backend API or daemon service needs to access another protected API without user interaction, the Client Credentials flow is used. In this scenario, the application itself authenticates with its Client ID and Client Secret (or certificate), without involving any user.

Configuration in Azure Entra ID:

  • Platform type: None (no Redirect URI needed)
  • Application type: Confidential client
  • OAuth flow: Client Credentials
  • Client Secret or Certificate: Yes — required
  • Permissions: Application permissions (not delegated)

Common scenarios:

  • Cron jobs and scheduled services that consume APIs
  • Microservice A calling Microservice B
  • CI/CD pipelines that access protected resources
  • Background daemons and workers

Example with Python (requests + MSAL):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# daemon_service.py — M2M service with Client Credentials
import os
import msal
import requests

# Daemon/service configuration
CLIENT_ID = os.environ["AZURE_CLIENT_ID"]
CLIENT_SECRET = os.environ["AZURE_CLIENT_SECRET"]
TENANT_ID = os.environ["AZURE_TENANT_ID"]
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"

# Target API scope — format: api://<client-id>/.default
API_SCOPE = ["api://api-destino-client-id/.default"]
API_BASE_URL = "https://api.seudominio.com"

def obter_token_m2m():
    """Gets an access token using Client Credentials (no user)."""
    app = msal.ConfidentialClientApplication(
        CLIENT_ID,
        authority=AUTHORITY,
        client_credential=CLIENT_SECRET,
    )

    # Tries to use a cached token before requesting a new one
    result = app.acquire_token_silent(API_SCOPE, account=None)
    if not result:
        # Requests a new token via Client Credentials
        result = app.acquire_token_for_client(scopes=API_SCOPE)

    if "access_token" in result:
        return result["access_token"]
    else:
        raise Exception(f"Failed to obtain token: {result.get('error_description')}")

def chamar_api_protegida():
    """Chama a API protegida usando o access token M2M."""
    token = obter_token_m2m()

    # Include the token in the Authorization header
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }

    response = requests.get(f"{API_BASE_URL}/api/dados", headers=headers)
    response.raise_for_status()
    return response.json()

if __name__ == "__main__":
    dados = chamar_api_protegida()
    print(f"Data received from the API: {dados}")

💡 Tip: For high-security production scenarios, prefer certificates over Client Secrets for authenticating M2M services. Certificates offer greater security and can be managed via Azure Key Vault.


Comparison Table: Which Client ID Type Should You Use?

This table summarizes the decisions you need to make when registering your application in Azure Entra ID:

CharacteristicSPA (Public Client)Server-Side (Confidential)REST API / Daemon (Confidential)
Where it runsUser’s browserWeb serverBackend server
Client SecretNoYesYes (or certificate)
OAuth flowAuth Code + PKCEAuth Code + SecretClient Credentials
User interactionYes (interactive login)Yes (interactive login)No (M2M)
Tokens receivedID Token + Access TokenID Token + Access TokenAccess Token only
Refresh TokenYes (with offline_access)YesNo (uses token cache)
App exampleAngular, React, VueFlask, ASP.NET, ExpressCron job, microservice, daemon
Platform in the portalSingle-page applicationWebNone (app permissions only)
MSAL library@azure/msal-angularmsal-python / MSAL.NETmsal-python / MSAL.NET

Protecting Your API with C#: Token Validation in ASP.NET Core

Regardless of which type of client calls your API, the REST API needs to validate the access token it receives. Here is how to do it in C# with ASP.NET Core using the Microsoft.Identity.Web package, which is Microsoft’s recommended way to protect APIs with Azure Entra ID.

First, create the project and install the dependencies:

1
2
3
4
5
6
7
# Create a Web API project
dotnet new webapi -n MinhaApiProtegida --framework net8.0
cd MinhaApiProtegida

# Install Microsoft Identity authentication packages
dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.MicrosoftGraph  # Optional: if you need to call Graph

Configuration (appsettings.json):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "seu-tenant-id",
    "ClientId": "api://seu-client-id-da-api",
    "Audience": "api://seu-client-id-da-api",
    "Scopes": "User.Read Admin.Full"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

Program.cs configuration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Program.cs — REST API protected with Azure Entra ID (ASP.NET Core 8)
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;

var builder = WebApplication.CreateBuilder(args);

// Configures JWT Bearer authentication with Azure Entra ID
// Microsoft.Identity.Web automatically takes care of:
// - Fetching public keys (JWKS) from Azure Entra ID
// - Validating the token's issuer, audience, signature and expiration
// - Validating scopes and roles
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

// Configure authorization policies based on roles and scopes
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("LeituraPermitida", policy =>
        policy.RequireScope("User.Read"))       // Requires the User.Read scope
    .AddPolicy("AdminOnly", policy =>
        policy.RequireRole("Admin"));            // Requires the Admin role

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Configure CORS to allow requests from the Angular SPA
builder.Services.AddCors(options =>
{
    options.AddPolicy("PermitirSPA", corsBuilder =>
    {
        corsBuilder
            .WithOrigins("http://localhost:4200", "https://app.seudominio.com")
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors("PermitirSPA");
app.UseAuthentication();  // Authentication middleware (validates the JWT)
app.UseAuthorization();   // Authorization middleware (checks policies)
app.MapControllers();

app.Run();

Controller with protected endpoints (DadosController.cs):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Controllers/DadosController.cs — Endpoints protected with granular authorization
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;

namespace MinhaApiProtegida.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]  // All endpoints require authentication by default
public class DadosController : ControllerBase
{
    /// <summary>
    /// Protected endpoint — requires a valid access token with the User.Read scope.
    /// Can be called by SPAs (delegated) or daemons (application).
    /// </summary>
    [HttpGet]
    [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] // Validates scope
    public IActionResult ObterDados()
    {
        // Extract information from the validated JWT token
        var usuario = User.GetDisplayName()
                     ?? User.FindFirst("preferred_username")?.Value
                     ?? "Unknown";

        var objectId = User.GetObjectId();             // Azure Entra OID
        var tenantId = User.GetTenantId();             // Tenant ID
        var scopes = User.FindFirst("scp")?.Value;     // Delegated scopes

        return Ok(new
        {
            Mensagem = "Access granted!",
            Usuario = usuario,
            ObjectId = objectId,
            TenantId = tenantId,
            Scopes = scopes,
            Timestamp = DateTime.UtcNow
        });
    }

    /// <summary>
    /// Admin endpoint — requires the 'Admin' role assigned in Azure Entra ID.
    /// </summary>
    [HttpGet("admin")]
    [Authorize(Policy = "AdminOnly")] // Requires the Admin role
    public IActionResult ObterDadosAdmin()
    {
        var roles = User.Claims
            .Where(c => c.Type == "roles" || c.Type == System.Security.Claims.ClaimTypes.Role)
            .Select(c => c.Value)
            .ToList();

        return Ok(new
        {
            Mensagem = "Welcome, administrator!",
            Roles = roles,
            Usuario = User.GetDisplayName()
        });
    }

    /// <summary>
    /// Endpoint that distinguishes delegated calls (user) from M2M calls (daemon).
    /// Useful when the same API is consumed by SPAs and backend services.
    /// </summary>
    [HttpGet("info")]
    public IActionResult InformacoesToken()
    {
        var scopeClaim = User.FindFirst("scp");        // Present in delegated tokens
        var rolesClaim = User.FindFirst("roles");      // Present in application tokens

        var tipoFluxo = scopeClaim != null
            ? "Delegated (user via SPA/Web App)"
            : "Application (M2M via Client Credentials)";

        return Ok(new
        {
            TipoFluxo = tipoFluxo,
            Issuer = User.FindFirst("iss")?.Value,
            Audience = User.FindFirst("aud")?.Value,
            Expiracao = User.FindFirst("exp")?.Value,
            Scopes = scopeClaim?.Value,
            Roles = rolesClaim?.Value
        });
    }
}

💡 Tip: The Microsoft.Identity.Web package greatly simplifies token validation in ASP.NET Core. It automatically fetches the JWKS keys from Azure Entra ID and validates issuer, audience, signature and expiration — all configured with a single line in Program.cs. In addition, extension methods such as User.GetDisplayName() and User.GetObjectId() make it easy to extract claims from the already validated JWT.


Tips and Good Practices

  • Always use PKCE for public applications: even if the framework does not require it, PKCE protects against authorization code interception attacks. Azure Entra ID supports PKCE for all flows.

  • Prefer certificates over Client Secrets in production: Client Secrets expire and can leak into logs. Certificates managed by Azure Key Vault are more secure and support automated rotation.

  • Define granular scopes in your API: instead of a single generic scope, create scopes such as User.Read, User.Write, Admin.Full to apply the principle of least privilege.

  • Validate ALL JWT fields in your API: do not rely on the signature alone. Validate iss, aud, exp, nbf and the scopes/roles required for each endpoint.

  • Use Managed Identities when possible: for services running on Azure (App Service, Functions, VMs), use Managed Identities instead of Client Secrets. This removes the need to manage credentials.

  • Configure appropriate expiration times: Access Tokens should be short-lived (default: 1 hour in Azure Entra). Use Refresh Tokens for renewal. Never extend the expiration time excessively.

  • Implement logout correctly: besides clearing tokens locally, redirect the user to the Azure Entra logout endpoint (/oauth2/v2.0/logout) to end the session at the identity provider.

⚠️ Warning: Never validate tokens only on the front end. The real validation must happen in the API (Resource Server). The front end may inspect the ID Token to display user information, but authorization always happens on the backend.


Conclusion

Understanding the difference between authentication and authorization is the foundation for building secure systems. JWT offers a compact, self-contained format for carrying identity and permission claims. OAuth 2.0 solves the problem of access delegation without exposing credentials, while OpenID Connect adds the identity layer that lets you know who the authenticated user is.

In practice, when using Azure Entra ID, choosing the correct Client ID type is decisive for your application’s security: SPA applications use public clients with PKCE, server-side applications use confidential clients with secrets, and APIs/daemons use the Client Credentials flow for machine-to-machine communication. And if the scenario requires integration with legacy systems, SAML 2.0 remains the appropriate protocol — many identity providers, including Azure Entra ID, support both protocols simultaneously.

The most important thing is to follow the principle that each application should have only the permissions required to perform its function. For SPAs that handle sensitive data, consider adopting the BFF (Backend For Frontend) pattern, which moves the tokens to the server — see how to implement it in BFF Backend For Frontend: Security in SPAs. If you need a free and open-source identity provider that supports OAuth 2.0, OpenID Connect and SAML 2.0 on your own infrastructure, check out Keycloak: Free Authentication with Containers and C#. If you enjoyed this content, leave a comment with your questions or share it with other developers. To deepen your knowledge of project automation, also check out Makefile: Automating tasks for Python, Hugo and Docker.


Read Also


References