top of page

OAuth 2 Grant Type

  • Writer: Anand Nerurkar
    Anand Nerurkar
  • Oct 23
  • 7 min read

Excellent 👏 — you’re referring to OAuth 2.0 Grant Types and their Flows, which are essential in any microservices modernization or cloud-native banking platform, especially when integrating with Azure AD, Keycloak, or Auth0.

Let’s go step-by-step — covering what each grant type is, how the flow works, when to use it, and how it fits into your microservices or API gateway design.

🔐 1. What Are “Grant Types”?

A grant type defines how a client (frontend or service) obtains an access token from the Authorization Server (Identity Provider) in OAuth 2.0.

Each type suits a different client:

  • Browser-based SPA (React/Angular)

  • Mobile App

  • Backend microservice

  • Machine-to-Machine (M2M)

  • Legacy app migrating to modern security

🧩 2. The Main OAuth 2.0 Grant Types

Grant Type

Used By

Secure?

Typical Use Case

Authorization Code (with PKCE)

Web, Mobile Apps

✅ High

User login flows (with redirect)

Client Credentials

Backend Services

✅ High

Service-to-service (M2M)

Resource Owner Password Credentials (ROPC)

Legacy / trusted apps

⚠️ Deprecated

Migration phase only

Refresh Token

Any client needing long session

✅ Medium

Token renewal

Device Code

Smart TVs, IoT

✅ Medium

Device login

Implicit Flow

SPAs (deprecated)

❌ Low

Replaced by Auth Code + PKCE

🔄 3. Authorization Code Flow (with PKCE)

🔧 Use Case:

User authenticates via browser — typical for React/Angular frontend calling Spring Boot microservices.

🧭 Flow Steps

  1. Frontend → Auth Server (Azure AD / Keycloak)Redirect user to /authorize endpoint with:

    response_type=code client_id=web-app redirect_uri=https://app/callback code_challenge=<PKCE_HASH>

  2. User logs in (via Azure AD or Keycloak login UI)

  3. Auth Server → FrontendRedirects back with authorization_code.

  4. Frontend → Auth Server (Token Endpoint)Exchanges the code + PKCE verifier for:

    • access_token

    • refresh_token

  5. Frontend → API Gateway / MicroserviceSends API call with:

    Authorization: Bearer <access_token>

  6. Microservice validates token (using public key / introspection).

🔒 Security:

  • PKCE = Proof Key for Code Exchange (prevents code interception).

  • Never exposes tokens in browser URLs.

  • Most secure for user-facing applications.

⚙️ 4. Client Credentials Flow (Service-to-Service)

🔧 Use Case:

Microservice A calls Microservice B securely — common in microservices ecosystems.

🧭 Flow Steps

  1. Service A → Auth ServerSends:

    grant_type=client_credentials client_id=service-a client_secret=abc123

  2. Auth Server → Service AReturns access_token.

  3. Service A → Service BSends request with:

    Authorization: Bearer <access_token>

  4. Service B validates token using public keys (JWKS) or introspection endpoint.

🔒 Security:

  • Token represents the service identity, not a user.

  • Best for internal APIs, Kafka consumers, or background batch jobs.

  • Tokens often scoped (e.g., scope=loan:read).

🧰 5. Resource Owner Password Credentials (ROPC) Flow

⚠️ Deprecated — Use Only for Legacy Integration

🔧 Use Case:

Legacy EJB/Oracle UI directly collects username/password (no browser redirect).

🧭 Flow Steps

  1. Client → Auth Server

    grant_type=password username=user1 password=pass123 client_id=legacy-app

  2. Auth Server → ClientReturns access_token.

  3. Client uses token to access microservices.

🔒 Security:

  • Insecure: app handles raw credentials.

  • Use only as temporary workaround during modernization.

  • Replace with Authorization Code + PKCE as soon as possible.

🔁 6. Refresh Token Flow

Used to get new access tokens without re-login.

🧭 Flow Steps

  1. Client already has a valid refresh_token.

  2. Client → Auth Server

    grant_type=refresh_token refresh_token=<token>

  3. Auth Server → ClientReturns new access_token.

🔒 Security:

  • Refresh tokens should be stored securely (encrypted).

  • In mobile/browser, use short-lived access tokens and silent refresh.

📺 7. Device Code Flow

Used for devices without browser or keyboard (e.g., ATM terminal, TV app).

🧭 Flow Steps:

  1. Device requests a device code.

  2. User logs in via browser (on another device).

  3. Device polls for token.

  4. Auth server issues access token.

⚙️ 8. How These Fit in Microservices Architecture

Layer

Typical Grant Type

Description

Frontend (React/Angular)

Authorization Code + PKCE

User login via Azure AD

API Gateway (Kong / Azure APIM)

Validates token

Checks JWT scopes

Internal Microservice Calls

Client Credentials

Service-to-service auth

Batch / Pro*C Jobs Modernized as Spring Batch

Client Credentials

Non-interactive jobs

Legacy Integration (temporary)

ROPC

To be replaced later

Mobile App

Authorization Code + PKCE

Mobile SDK-based auth

Event-driven Services

Client Credentials

Kafka consumers authenticate to broker

🔐 9. Token Validation Patterns

Pattern

Description

Implementation

JWT Local Validation

Verify signature using public key (JWKS)

Spring Boot Resource Server + Nimbus JOSE

Introspection Endpoint

Call Auth Server /introspect

Used when tokens are opaque

Token Exchange

Exchange one token for another (cross-domain)

For hybrid cloud multi-tenant cases

🧱 10. Example: Banking Microservices Flow

[User] → [React App]
   ↓ (Auth Code + PKCE)
[Azure AD / Keycloak] → Issues access_token (JWT)
   ↓
[API Gateway] → Validates JWT (scope: loan:write)
   ↓
[Loan-Service] → Calls Credit-Service
   ↓ (Client Credentials)
[Auth Server] → Issues service token (scope: credit:read)
   ↓
[Credit-Service] → Returns credit score

🧩 11. Tools & Frameworks

Purpose

Tools / Frameworks

Authorization Server

Azure AD, Keycloak, Auth0, Okta, Ping Identity

Token Validation

Spring Security OAuth2 Resource Server, Nimbus JOSE, Kong Gateway, APIM

API Gateway Policy

Azure API Management, Kong, Apigee

Identity Federation

OpenID Connect, SAML 2.0

Service Auth

mTLS, Client Credentials, OPA Policy Enforcement

🧠 12. Interview-Ready Summary

“We implemented OAuth2-based tokenization across our microservices landscape.Frontend apps use Authorization Code with PKCE for user login through Azure AD,internal service-to-service calls use Client Credentials flow,and legacy systems temporarily use ROPC flow during migration.All microservices validate JWTs locally using Azure AD’s public keys via Spring Security Resource Server,ensuring zero trust, scoped access, and no credential sharing.”

🧩 Context

In OAuth 2.0 or OpenID Connect, tokens (access tokens, refresh tokens, ID tokens) are what let users or systems access protected APIs.Because they are bearer tokens — anyone who has them can use them — securing them is critical.

⚠️ 1️⃣ Common Token Attack Scenarios

Threat

Description

Example

Token theft (interception)

Attacker intercepts token over insecure channel

HTTP instead of HTTPS

Token replay

Attacker reuses a valid token later

Token captured from logs

Cross-site scripting (XSS)

Malicious script accesses tokens from browser storage

SPA with weak Content Security Policy

Refresh token abuse

Long-lived refresh token stolen

Stored in local storage unencrypted

Phishing / redirect URI manipulation

Rogue redirect URI steals authorization code

Misconfigured OAuth redirect URI

Man-in-the-middle (MITM)

Attacker intercepts between client and auth server

Improper certificate validation

🛡️ 2️⃣ Core Token Protection Mechanisms

✅ (a) Use HTTPS/TLS for every token exchange

Never exchange tokens over HTTP. Enforce TLS 1.2+.

✅ (b) Use short-lived access tokens

  • Keep access tokens valid for 5–15 minutes only.

  • Combine with refresh tokens that are bound and revocable.

✅ (c) Implement Proof-of-Possession (DPoP) or mTLS

Instead of a plain bearer token, bind tokens to a client certificate or key.

Mechanism

Description

DPoP

Access token includes a public key thumbprint; client signs requests with the private key. Prevents reuse if stolen.

mTLS

Mutual TLS ensures only the certificate-bound client can use the token.

✅ (d) Use PKCE (Proof Key for Code Exchange) for public clients

Prevents code interception attacks in mobile or SPA flows.

Flow:

  1. Client generates code_verifier and hash code_challenge.

  2. Sends code_challenge in /authorize request.

  3. Later, exchanges code for token using code_verifier.→ Attacker who intercepts authorization code cannot use it.

✅ (e) Use audience & issuer validation

APIs must verify that:

  • The token’s aud (audience) matches their API identifier.

  • The token’s iss (issuer) is the trusted authorization server.

✅ (f) Use JWT signature and encryption

  • Access tokens are JWTs signed with private key (RS256 or ES256).

  • APIs validate signature before trusting claims.

  • Optionally, encrypt tokens (JWE) if sensitive info exists.

✅ (g) Token storage hygiene

For browser apps:

  • Never store tokens in localStorage or sessionStorage.

  • Use HTTP-only secure cookies.For backend or mobile apps:

  • Use secure OS keystore / vaults (e.g., Azure Key Vault, AWS Secrets Manager).

✅ (h) Rotate keys (JWKS rotation)

Use short-lived signing keys, rotate frequently via JWKS endpoint.Invalidate old tokens after rotation if possible.

✅ (i) Centralized token introspection and revocation

  • Maintain introspection endpoint (/introspect) to validate tokens.

  • Use refresh token rotation — issue new refresh token each time.

✅ (j) Threat detection

  • Detect token anomalies: usage from multiple IPs, geographies, or devices.

  • Use SIEM tools (e.g., Azure Sentinel, Splunk) to correlate anomalies.

🧰 3️⃣ Practical Example (Banking Microservices)

Area

Control

API Gateway

Validates JWT signature, audience, and expiration.

Microservices

Use opaque tokens internally; introspect via identity service.

Refresh Token

Bound to client + device fingerprint. Rotated every use.

Storage

Stored in encrypted cache (Redis) or database with AES-256.

Transport

Mutual TLS enforced between services.

Revocation

Central token blacklist for compromised tokens.

🧠 4️⃣ In summary:

To prevent token hacking:

Bind + Encrypt + Limit + Validate + Rotate + Monitor

Short version:

HTTPS only Short-lived tokens DPoP or mTLS PKCE for code flow Validate aud & iss Store securely (no localStorage) Rotate & revoke Detect anomalies

Perfect 👍 — here’s a secure OAuth 2.0 Authorization Code Flow with PKCE + mTLS + Refresh Token Rotation sequence, commonly used in banking microservices where security and compliance are critical.

🧩 Actors

  • 👤 User (Customer)

  • 🌐 Frontend App (Public Client - SPA or Mobile)

  • 🔐 Authorization Server (e.g., Azure AD / Keycloak / PingID)

  • 🚪 API Gateway

  • ⚙️ Microservice (e.g., Account / Loan Service)

  • 🧱 mTLS + Token Introspection Service

🔄 Sequence Diagram (Text Representation)

User              Frontend App              Auth Server               API Gateway           Microservice
 |                     |                         |                          |                      |
 |-- 1. Login Request ->|                         |                          |                      |
 |                     |-- 2. /authorize?code_challenge -->|                 |                      |
 |                     |                         |-- 3. Authenticates user  |                      |
 |                     |                         |<-- 4. Auth code ---------|                      |
 |                     |-- 5. /token (code_verifier + mTLS cert) ----------->|                      |
 |                     |                         |-- 6. Validate cert (mTLS)                        |
 |                     |                         |-- 7. Issue short-lived JWT Access Token & Refresh|
 |                     |<------------------------|                         |                      |
 |                     |-- 8. API Call (Bearer token + DPoP/mTLS) --------->|                      |
 |                     |                         |-- 9. Validate JWT (iss, aud, exp, sig)          |
 |                     |                         |-- 10. Token introspection (optional) ----------->|
 |                     |                         |                          |-- 11. Validate active token |
 |                     |                         |                          |<-- 12. OK --------------|
 |                     |                         |-- 13. Forward request -------------------------->|
 |                     |                         |                          |--> 14. Process request |
 |                     |                         |                          |<-- 15. Response -------|
 |<-----------------------------------------------------------------------------------------------|
 |                     |                         |                          |                      |
 |-- 16. After expiry, /token (refresh) with rotation --------------------->|                      |
 |                     |                         |-- 17. Revoke old refresh token                  |
 |                     |                         |-- 18. Issue new Access + Refresh Token ---------|
 |                     |<------------------------|                         |                      |

🔒 Key Security Elements

Layer

Mechanism

Purpose

Frontend

PKCE (code_challenge + code_verifier)

Prevents code interception attacks

Transport

mTLS / HTTPS

Prevents MITM and ensures client authenticity

Token

JWT (RS256 / ES256 signed)

Verifiable, tamper-proof access

Microservices

Token introspection

Central validation of token activity

Refresh Rotation

New refresh token each use

Prevents replay attacks

Gateway

DPoP or Certificate pinning

Proof of possession binding

Monitoring

SIEM + token usage telemetry

Detects token anomalies or misuse

⚙️ Example Access Token (JWT Claims)

{
  "iss": "https://auth.bank.com",
  "sub": "user123",
  "aud": "https://api.bank.com/account",
  "exp": 1739980800,
  "client_id": "bank-frontend-app",
  "cnf": {
    "x5t#S256": "abc123xyz"  // Certificate thumbprint for mTLS binding
  },
  "scope": "read:account write:transfer"
}

🧰 Tools Used in Implementation

Area

Tool / Platform

Authorization Server

Azure AD B2C, Keycloak, Okta, or Auth0

Token Validation

Spring Security OAuth2 Resource Server, Istio Envoy JWT filter

API Gateway

Kong, Apigee, Azure API Management, or Istio Gateway

Secrets

Azure Key Vault, AWS KMS, HashiCorp Vault

Monitoring

Azure Sentinel, Splunk, ELK Stack

🧠 Outcome

✅ Secure against token theft, replay, interception, and misuse.✅ Meets RBI/SEBI data protection & security guidelines.✅ Enables zero-trust microservice-to-microservice communication.


ree

 
 
 

Recent Posts

See All
How to replan- No outcome after 6 month

⭐ “A transformation program is running for 6 months. Business says it is not delivering the value they expected. What will you do?” “When business says a 6-month transformation isn’t delivering value,

 
 
 
EA Strategy in case of Merger

⭐ EA Strategy in Case of a Merger (M&A) My EA strategy for a merger focuses on four pillars: discover, decide, integrate, and optimize.The goal is business continuity + synergy + tech consolidation. ✅

 
 
 

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
  • Facebook
  • Twitter
  • LinkedIn

©2024 by AeeroTech. Proudly created with Wix.com

bottom of page