OAuth 2 Grant Type
- 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
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>
User logs in (via Azure AD or Keycloak login UI)
Auth Server â FrontendRedirects back with authorization_code.
Frontend â Auth Server (Token Endpoint)Exchanges the code + PKCE verifier for:
access_token
refresh_token
Frontend â API Gateway / MicroserviceSends API call with:
Authorization: Bearer <access_token>
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
Service A â Auth ServerSends:
grant_type=client_credentials client_id=service-a client_secret=abc123
Auth Server â Service AReturns access_token.
Service A â Service BSends request with:
Authorization: Bearer <access_token>
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
Client â Auth Server
grant_type=password username=user1 password=pass123 client_id=legacy-app
Auth Server â ClientReturns access_token.
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
Client already has a valid refresh_token.
Client â Auth Server
grant_type=refresh_token refresh_token=<token>
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:
Device requests a device code.
User logs in via browser (on another device).
Device polls for token.
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:
Client generates code_verifier and hash code_challenge.
Sends code_challenge in /authorize request.
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.

.png)

Comments