Configuring OAuth 2.0 Authorization Flow
Overview
Configure secure OAuth 2.0 authorization flows including Authorization Code with PKCE, Client Credentials, and Device Authorization Grant. This skill covers flow selection, PKCE implementation, token lifecycle management, scope design, and alignment with OAuth 2.1 security requirements.
Anti-Rationalization Table
| Rationalization |
Reality |
| "I'll figure it out as I go" |
A structured approach saves time and reduces errors. Follow the workflow in this skill rather than improvising. |
| "I already know this topic" |
Familiarity breeds shortcuts. Use the checklist to verify you haven't missed critical steps. |
| "This doesn't apply to my situation" |
The patterns here generalize across contexts. Adapt, don't skip — the underlying principles hold. |
| "One more tool will fix it" |
Adding complexity rarely solves process gaps. Master the core workflow first. |
When to Use
Trigger phrases:
"configuring oauth2 authorization flow"
"Configure secure OAuth 2"
When deploying or configuring configuring oauth2 authorization flow capabilities in your environment
When establishing security controls aligned to compliance requirements
When building or improving security architecture for this domain
When conducting security assessments that require this implementation
Prerequisites
- Familiarity with identity access management concepts and tools
- Access to a test or lab environment for safe execution
- Python 3.8+ with required dependencies installed
- Appropriate authorization for any testing activities
Objectives
- Implement Authorization Code flow with PKCE for public and confidential clients
- Configure Client Credentials flow for machine-to-machine communication
- Design least-privilege scope hierarchies
- Implement secure token storage, refresh, and revocation
- Apply OAuth 2.1 best practices and RFC 9700 security recommendations
- Validate token integrity and prevent common OAuth attacks
Key Concepts
This section covers key concepts for configuring oauth2 authorization flow.
- Ensure all prerequisites are met before proceeding
- Follow the documented workflow steps in sequence
- Record results and any anomalies encountered during this phase
OAuth 2.0 Grant Types
- Authorization Code + PKCE: Recommended for all client types (web, mobile, SPA). PKCE is mandatory in OAuth 2.1.
- Client Credentials: Machine-to-machine authentication without user context.
- Device Authorization Grant (RFC 8628): For input-constrained devices (smart TVs, CLI tools).
- Refresh Token: Long-lived token to obtain new access tokens without re-authentication.
PKCE (Proof Key for Code Exchange)
PKCE (RFC 7636) prevents authorization code interception attacks:
- Client generates random
code_verifier (43-128 characters, unreserved URI chars)
- Client computes
code_challenge = BASE64URL(SHA256(code_verifier))
- Authorization request includes
code_challenge and code_challenge_method=S256
- Token request includes original
code_verifier
- Server validates
SHA256(code_verifier) matches stored code_challenge
Token Types
- Access Token: Short-lived (5-60 min), bearer or DPoP-bound
- Refresh Token: Long-lived, single-use with rotation
- ID Token (OIDC): JWT containing user identity claims
Workflow
# Example: IOC detection
import re
IOC_PATTERNS = {
"ip": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
"domain": r"\b[a-z0-9-]+\.[a-z]{2,}\b",
"hash_md5": r"\b[a-f0-9]{32}\b",
"hash_sha256": r"\b[a-f0-9]{64}\b",
}
def extract_iocs(text: str) -> dict:
return {k: re.findall(v, text) for k, v in IOC_PATTERNS.items()}
- Scope the task — define objectives, boundaries, and success criteria
- Gather information — collect all necessary data and context before proceeding
- Execute the core workflow — follow the domain-specific steps methodically
- Validate results — verify outputs against expected outcomes or baselines
- Document findings — record results, anomalies, and recommendations
Step 1: Authorization Code Flow with PKCE
- Generate cryptographically random code_verifier (min 43 chars)
- Compute code_challenge using S256 method
- Redirect user to authorization endpoint with parameters:
- response_type=code
- client_id, redirect_uri, scope, state
- code_challenge, code_challenge_method=S256
- User authenticates and consents
- Authorization server redirects with authorization code
- Exchange code + code_verifier for tokens at token endpoint
- Validate state parameter matches original value
Step 2: Scope Design
- Define granular scopes:
read:users, write:orders, admin:settings
- Follow least-privilege: request minimum scopes needed
- Implement scope validation on resource server
- Document scope hierarchy and consent requirements
Step 3: Token Security
- Store tokens securely (httpOnly cookies for web, keychain for mobile)
- Implement token refresh with rotation (one-time-use refresh tokens)
- Set appropriate expiration: access tokens 5-15 min, refresh tokens 8-24 hrs
- Enable DPoP (Demonstration of Proof-of-Possession) for sender-constrained tokens
- Implement token revocation endpoint
Step 4: Client Credentials Flow
- Register service client with client_id and client_secret
- Request token: POST /oauth/token with grant_type=client_credentials
- Include scope for required permissions
- Store client_secret securely (vault, env vars, not code)
- Implement certificate-based client authentication for higher assurance
Step 5: Security Hardening
- Enforce PKCE for all authorization code flows
- Use exact redirect URI matching (no wildcards)
- Implement CSRF protection with state parameter
- Enable refresh token rotation and revocation on reuse detection
- Apply RFC 9700 security best practices
- Block implicit grant and ROPC (removed in OAuth 2.1)
Security Controls
| Control |
NIST 800-53 |
Description |
| Access Control |
AC-3 |
Token-based access enforcement |
| Authentication |
IA-5 |
Client credential management |
| Session Management |
SC-23 |
Token lifecycle management |
| Audit |
AU-3 |
Log all token issuance and revocation |
| Cryptographic Protection |
SC-13 |
PKCE and token signing |
Common Pitfalls
- Using implicit grant (removed in OAuth 2.1) instead of authorization code + PKCE
- Storing tokens in localStorage (XSS vulnerable) instead of httpOnly cookies
- Not validating state parameter enabling CSRF attacks
- Using wildcard redirect URIs allowing open redirect exploitation
- Not implementing refresh token rotation allowing token theft persistence
Verification
When NOT to Use
- You need to implement from scratch (use implementing-* skills)
- Task is about testing the configuration (use performing-* skills)
- You need to analyze misconfigurations (use analyzing-* skills)
- Task is about building automation (use building-* skills)
- You don't have admin access to the system
- Task requires vendor professional services
Red Flags
- Performing actions without explicit written authorization from the asset owner
- Testing against production systems without a defined scope and rules of engagement
- Sharing sensitive findings or credentials in unencrypted communications
- Failing to properly scope and contain the assessment before starting
Process
- Analyze the task requirements
- Apply domain expertise
- Verify output quality
1---2name: configuring-oauth2-authorization-flow3description: Use when configuring secure OAuth 2.0 authorization flows including Authorization Code with PKCE, Client Credentials, and Device Authorization Grant. This skill covers flow selection, PKCE implementation, token4license: Apache-2.05---67# Configuring OAuth 2.0 Authorization Flow89## Overview10Configure secure OAuth 2.0 authorization flows including Authorization Code with PKCE, Client Credentials, and Device Authorization Grant. This skill covers flow selection, PKCE implementation, token lifecycle management, scope design, and alignment with OAuth 2.1 security requirements.11121314## Anti-Rationalization Table1516| Rationalization | Reality |17|---|---|18| "I'll figure it out as I go" | A structured approach saves time and reduces errors. Follow the workflow in this skill rather than improvising. |19| "I already know this topic" | Familiarity breeds shortcuts. Use the checklist to verify you haven't missed critical steps. |20| "This doesn't apply to my situation" | The patterns here generalize across contexts. Adapt, don't skip — the underlying principles hold. |21| "One more tool will fix it" | Adding complexity rarely solves process gaps. Master the core workflow first. |2223## When to Use24**Trigger phrases:**25- "configuring oauth2 authorization flow"26- "Configure secure OAuth 2"272829- When deploying or configuring configuring oauth2 authorization flow capabilities in your environment30- When establishing security controls aligned to compliance requirements31- When building or improving security architecture for this domain32- When conducting security assessments that require this implementation3334## Prerequisites3536- Familiarity with identity access management concepts and tools37- Access to a test or lab environment for safe execution38- Python 3.8+ with required dependencies installed39- Appropriate authorization for any testing activities4041## Objectives42- Implement Authorization Code flow with PKCE for public and confidential clients43- Configure Client Credentials flow for machine-to-machine communication44- Design least-privilege scope hierarchies45- Implement secure token storage, refresh, and revocation46- Apply OAuth 2.1 best practices and RFC 9700 security recommendations47- Validate token integrity and prevent common OAuth attacks4849## Key Concepts5051This section covers key concepts for configuring oauth2 authorization flow.5253- Ensure all prerequisites are met before proceeding54- Follow the documented workflow steps in sequence55- Record results and any anomalies encountered during this phase56### OAuth 2.0 Grant Types571. **Authorization Code + PKCE**: Recommended for all client types (web, mobile, SPA). PKCE is mandatory in OAuth 2.1.582. **Client Credentials**: Machine-to-machine authentication without user context.593. **Device Authorization Grant (RFC 8628)**: For input-constrained devices (smart TVs, CLI tools).604. **Refresh Token**: Long-lived token to obtain new access tokens without re-authentication.6162### PKCE (Proof Key for Code Exchange)63PKCE (RFC 7636) prevents authorization code interception attacks:641. Client generates random `code_verifier` (43-128 characters, unreserved URI chars)652. Client computes `code_challenge = BASE64URL(SHA256(code_verifier))`663. Authorization request includes `code_challenge` and `code_challenge_method=S256`674. Token request includes original `code_verifier`685. Server validates `SHA256(code_verifier)` matches stored `code_challenge`6970### Token Types71- **Access Token**: Short-lived (5-60 min), bearer or DPoP-bound72- **Refresh Token**: Long-lived, single-use with rotation73- **ID Token (OIDC)**: JWT containing user identity claims7475## Workflow7677```python78# Example: IOC detection79import re8081IOC_PATTERNS = {82 "ip": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",83 "domain": r"\b[a-z0-9-]+\.[a-z]{2,}\b",84 "hash_md5": r"\b[a-f0-9]{32}\b",85 "hash_sha256": r"\b[a-f0-9]{64}\b",86}8788def extract_iocs(text: str) -> dict:89 return {k: re.findall(v, text) for k, v in IOC_PATTERNS.items()}90```91921. **Scope the task** — define objectives, boundaries, and success criteria932. **Gather information** — collect all necessary data and context before proceeding943. **Execute the core workflow** — follow the domain-specific steps methodically954. **Validate results** — verify outputs against expected outcomes or baselines965. **Document findings** — record results, anomalies, and recommendations97### Step 1: Authorization Code Flow with PKCE981. Generate cryptographically random code_verifier (min 43 chars)992. Compute code_challenge using S256 method1003. Redirect user to authorization endpoint with parameters:101 - response_type=code102 - client_id, redirect_uri, scope, state103 - code_challenge, code_challenge_method=S2561044. User authenticates and consents1055. Authorization server redirects with authorization code1066. Exchange code + code_verifier for tokens at token endpoint1077. Validate state parameter matches original value108109### Step 2: Scope Design110- Define granular scopes: `read:users`, `write:orders`, `admin:settings`111- Follow least-privilege: request minimum scopes needed112- Implement scope validation on resource server113- Document scope hierarchy and consent requirements114115### Step 3: Token Security116- Store tokens securely (httpOnly cookies for web, keychain for mobile)117- Implement token refresh with rotation (one-time-use refresh tokens)118- Set appropriate expiration: access tokens 5-15 min, refresh tokens 8-24 hrs119- Enable DPoP (Demonstration of Proof-of-Possession) for sender-constrained tokens120- Implement token revocation endpoint121122### Step 4: Client Credentials Flow1231. Register service client with client_id and client_secret1242. Request token: POST /oauth/token with grant_type=client_credentials1253. Include scope for required permissions1264. Store client_secret securely (vault, env vars, not code)1275. Implement certificate-based client authentication for higher assurance128129### Step 5: Security Hardening130- Enforce PKCE for all authorization code flows131- Use exact redirect URI matching (no wildcards)132- Implement CSRF protection with state parameter133- Enable refresh token rotation and revocation on reuse detection134- Apply RFC 9700 security best practices135- Block implicit grant and ROPC (removed in OAuth 2.1)136137## Security Controls138| Control | NIST 800-53 | Description |139|---------|-------------|-------------|140| Access Control | AC-3 | Token-based access enforcement |141| Authentication | IA-5 | Client credential management |142| Session Management | SC-23 | Token lifecycle management |143| Audit | AU-3 | Log all token issuance and revocation |144| Cryptographic Protection | SC-13 | PKCE and token signing |145146## Common Pitfalls147- Using implicit grant (removed in OAuth 2.1) instead of authorization code + PKCE148- Storing tokens in localStorage (XSS vulnerable) instead of httpOnly cookies149- Not validating state parameter enabling CSRF attacks150- Using wildcard redirect URIs allowing open redirect exploitation151- Not implementing refresh token rotation allowing token theft persistence152153## Verification154- [ ] Authorization Code + PKCE flow completes successfully155- [ ] PKCE code_challenge validated at token endpoint156- [ ] State parameter prevents CSRF157- [ ] Access tokens expire within configured lifetime158- [ ] Refresh token rotation issues new refresh token each use159- [ ] Token revocation invalidates both access and refresh tokens160- [ ] Client Credentials flow works for service-to-service calls161- [ ] Scopes correctly enforced at resource server162## When NOT to Use163164- You need to implement from scratch (use implementing-* skills)165- Task is about testing the configuration (use performing-* skills)166- You need to analyze misconfigurations (use analyzing-* skills)167- Task is about building automation (use building-* skills)168- You don't have admin access to the system169- Task requires vendor professional services170171172## Red Flags173174- Performing actions without explicit written authorization from the asset owner175- Testing against production systems without a defined scope and rules of engagement176- Sharing sensitive findings or credentials in unencrypted communications177- Failing to properly scope and contain the assessment before starting178179## Process1801811. Analyze the task requirements1822. Apply domain expertise1833. Verify output quality