
Configuring Oauth2 Authorization Flow
- 166 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
configuring-oauth2-authorization-flow is a Claude Code skill in the AI & Agent Building category.
- configuring-oauth2-authorization-flow
- AI & Agent Building
- AI-coding skill
Configuring Oauth2 Authorization Flow by the numbers
- 166 all-time installs (skills.sh)
- +12 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,187 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill configuring-oauth2-authorization-flowAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 166 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
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.
When to Use
- 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
OAuth 2.0 Grant Types
1. Authorization Code + PKCE: Recommended for all client types (web, mobile, SPA). PKCE is mandatory in OAuth 2.1. 2. Client Credentials: Machine-to-machine authentication without user context. 3. Device Authorization Grant (RFC 8628): For input-constrained devices (smart TVs, CLI tools). 4. 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: 1. Client generates random code_verifier (43-128 characters, unreserved URI chars) 2. Client computes code_challenge = BASE64URL(SHA256(code_verifier)) 3. Authorization request includes code_challenge and code_challenge_method=S256 4. Token request includes original code_verifier 5. 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
Step 1: Authorization Code Flow with PKCE
1. Generate cryptographically random code_verifier (min 43 chars) 2. Compute code_challenge using S256 method 3. Redirect user to authorization endpoint with parameters:
- response_type=code
- client_id, redirect_uri, scope, state
- code_challenge, code_challenge_method=S256
4. User authenticates and consents 5. Authorization server redirects with authorization code 6. Exchange code + code_verifier for tokens at token endpoint 7. 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
1. Register service client with client_id and client_secret 2. Request token: POST /oauth/token with grant_type=client_credentials 3. Include scope for required permissions 4. Store client_secret securely (vault, env vars, not code) 5. 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
- [ ] Authorization Code + PKCE flow completes successfully
- [ ] PKCE code_challenge validated at token endpoint
- [ ] State parameter prevents CSRF
- [ ] Access tokens expire within configured lifetime
- [ ] Refresh token rotation issues new refresh token each use
- [ ] Token revocation invalidates both access and refresh tokens
- [ ] Client Credentials flow works for service-to-service calls
- [ ] Scopes correctly enforced at resource server
OAuth 2.0 Authorization Flow Configuration Template
Application Registration
| Field | Value |
|---|---|
| Application Name | |
| Client ID | |
| Client Type | [ ] Public [ ] Confidential |
| Grant Types | [ ] Authorization Code [ ] Client Credentials [ ] Refresh Token [ ] Device Code |
| PKCE Required | [ ] Yes (mandatory for OAuth 2.1) |
Redirect URI Configuration
| Environment | URI | Status |
|---|---|---|
| Development | http://localhost:3000/callback | [ ] Registered |
| Staging | https://staging.example.com/callback | [ ] Registered |
| Production | https://app.example.com/callback | [ ] Registered |
Rules:
- Exact match only - no wildcards
- HTTPS required for non-localhost URIs
- Each URI must be explicitly registered
Scope Design
| Scope | Description | Sensitivity |
|---|---|---|
| openid | OpenID Connect identity | Low |
| profile | User profile information | Low |
| User email address | Low | |
| read:users | Read user records | Medium |
| write:users | Modify user records | High |
| admin:settings | Modify system settings | Critical |
Token Configuration
| Parameter | Value | Justification |
|---|---|---|
| Access Token Lifetime | 15 minutes | Minimize window of exposure |
| Refresh Token Lifetime | 8 hours | Align with business hours |
| Refresh Token Rotation | Enabled | Detect token theft via reuse |
| Refresh Token Absolute Expiry | 24 hours | Force re-authentication daily |
| ID Token Lifetime | 5 minutes | Only used for initial authentication |
| Token Format | JWT (signed) | Enable stateless validation |
| Signing Algorithm | RS256 | Asymmetric verification |
Security Checklist
- [ ] PKCE enforced for all authorization code flows
- [ ] Implicit grant disabled
- [ ] ROPC (password) grant disabled
- [ ] State parameter validated
- [ ] Exact redirect URI matching enforced
- [ ] Refresh token rotation enabled
- [ ] Token revocation endpoint active
- [ ] DPoP enabled for high-security APIs
- [ ] Consent screen configured for sensitive scopes
- [ ] Token introspection secured with authentication
Client Authentication Methods
| Method | Use Case | Security Level |
|---|---|---|
| none | Public clients (SPA, mobile) | Requires PKCE |
| client_secret_basic | Server-side web apps | Medium |
| client_secret_post | Server-side web apps | Medium |
| private_key_jwt | High-security services | High |
| tls_client_auth | mTLS-capable services | High |
Monitoring & Alerting
- [ ] Token issuance rate monitoring
- [ ] Failed authentication attempts tracking
- [ ] Refresh token reuse detection alerts
- [ ] Scope escalation attempt alerts
- [ ] Unusual client_id activity monitoring
- [ ] Geographic anomaly detection for token usage
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
OAuth 2.0 Authorization Flow — API Reference
Libraries
| Library | Install | Purpose |
|---|---|---|
| requests | pip install requests | HTTP client for OAuth endpoints |
| authlib | pip install authlib | Full OAuth 2.0 / OIDC client library |
| PyJWT | pip install PyJWT[crypto] | JWT token validation and inspection |
OIDC Discovery Endpoint
GET {issuer}/.well-known/openid-configurationReturns: authorization_endpoint, token_endpoint, jwks_uri, supported grant types, scopes.
OAuth 2.0 Grant Types
| Grant Type | Use Case | Security |
|---|---|---|
| authorization_code | Server-side apps | Recommended with PKCE |
| client_credentials | Machine-to-machine | Service accounts only |
| implicit | (DEPRECATED) SPAs | Avoid — tokens in URL fragment |
| password | (DEPRECATED) Legacy | Avoid — credentials exposed to client |
| urn:ietf:params:oauth:grant-type:device_code | IoT/CLI | Approved for limited-input devices |
Security Best Practices
| Practice | RFC |
|---|---|
| PKCE (Proof Key for Code Exchange) | RFC 7636 |
| Token Binding | RFC 8471 |
| DPoP (Demonstrating Proof of Possession) | RFC 9449 |
| Sender-Constrained Tokens | OAuth 2.0 Security BCP |
External References
Standards and References - OAuth 2.0 Authorization Flow
Core OAuth Standards
- RFC 6749: The OAuth 2.0 Authorization Framework
- https://datatracker.ietf.org/doc/html/rfc6749
- RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage
- https://datatracker.ietf.org/doc/html/rfc6750
- RFC 7636: Proof Key for Code Exchange (PKCE)
- https://datatracker.ietf.org/doc/html/rfc7636
- RFC 9700: OAuth 2.0 Security Best Current Practice
- https://datatracker.ietf.org/doc/html/rfc9700
- OAuth 2.1 Draft: Consolidation of OAuth 2.0 with PKCE mandatory
- https://oauth.net/2.1/
Token Standards
- RFC 7519: JSON Web Token (JWT)
- https://datatracker.ietf.org/doc/html/rfc7519
- RFC 7515: JSON Web Signature (JWS)
- https://datatracker.ietf.org/doc/html/rfc7515
- RFC 9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP)
- https://datatracker.ietf.org/doc/html/rfc9449
- RFC 7009: OAuth 2.0 Token Revocation
- https://datatracker.ietf.org/doc/html/rfc7009
OpenID Connect
- OpenID Connect Core 1.0: Authentication layer on OAuth 2.0
- https://openid.net/specs/openid-connect-core-1_0.html
- OpenID Connect Discovery: Provider metadata discovery
- https://openid.net/specs/openid-connect-discovery-1_0.html
Additional Grant Types
- RFC 8628: OAuth 2.0 Device Authorization Grant
- https://datatracker.ietf.org/doc/html/rfc8628
NIST Standards
- NIST SP 800-63B: Digital Identity Guidelines - Authentication
- NIST SP 800-53 Rev 5:
- AC-3: Access Enforcement
- IA-5: Authenticator Management
- SC-13: Cryptographic Protection
- SC-23: Session Authenticity
- AU-3: Content of Audit Records
Implementation Guides
- Auth0 PKCE Guide: https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce
- Microsoft OIDC Flow: https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow
- Okta OAuth Express: https://developer.okta.com/blog/2025/07/28/express-oauth-pkce
- PKCE Explained: https://oauth.net/2/pkce/
Security References
- OWASP OAuth 2.0 Security: Common vulnerabilities and mitigations
- OAuth Security Workshop: Annual research on OAuth attack vectors
OAuth 2.0 Authorization Flow Workflows
Workflow 1: Authorization Code Flow with PKCE
Client Auth Server Resource Server
| | |
|-- Generate code_verifier --| |
|-- Compute code_challenge --| |
| | |
|--- AuthZ Request --------->| |
| (code_challenge, state) | |
| |-- User Authenticates -->|
| |<- User Consents --------|
|<-- AuthZ Code + state -----| |
| | |
|--- Token Request --------->| |
| (code + code_verifier) | |
|<-- Access + Refresh Token--| |
| | |
|--- API Request (Bearer) ---|------------------------>|
|<-- API Response ---------- |<------------------------|Step-by-Step:
1. Client generates code_verifier: random 43-128 char string (A-Z, a-z, 0-9, -._~) 2. Client computes code_challenge = BASE64URL(SHA256(code_verifier)) 3. Client redirects to: GET /authorize?response_type=code&client_id=xxx&redirect_uri=xxx&scope=xxx&state=RANDOM&code_challenge=xxx&code_challenge_method=S256 4. User authenticates and consents at authorization server 5. Server redirects to: redirect_uri?code=AUTH_CODE&state=RANDOM 6. Client validates state matches original 7. Client exchanges code: POST /token with grant_type=authorization_code&code=AUTH_CODE&code_verifier=xxx&redirect_uri=xxx 8. Server validates SHA256(code_verifier) matches stored code_challenge 9. Server returns access_token, refresh_token, id_token (if OIDC)
Workflow 2: Client Credentials Flow (Machine-to-Machine)
Service A Auth Server Service B (API)
| | |
|--- Token Request --------->| |
| (client_id, secret, scope)| |
|<-- Access Token -----------| |
| | |
|--- API Request (Bearer) ---|------------------------>|
|<-- API Response ---------- |<------------------------|Step-by-Step:
1. Service registers with auth server (client_id + client_secret) 2. Service requests token: POST /token with grant_type=client_credentials&scope=api:read 3. Auth server validates client credentials 4. Auth server returns access_token (no refresh token, no user context) 5. Service calls API with Authorization: Bearer ACCESS_TOKEN
Workflow 3: Token Refresh with Rotation
Client Auth Server
| |
|--- Refresh Request ------->|
| (refresh_token_v1) |
|<-- New Access Token -------|
|<-- New Refresh Token (v2) -|
| (v1 invalidated) |
| |
|--- Refresh Request ------->|
| (refresh_token_v2) |
|<-- New Access Token -------|
|<-- New Refresh Token (v3) -|
| |
|--- THEFT: Reuse v1 ------->|
| (DETECTED: v1 reused) |
|<-- REVOKE ALL TOKENS ------|Rotation Detection:
- Each refresh token is single-use
- On reuse of an old refresh token, server detects theft
- All tokens in the grant chain are revoked
- User must re-authenticate
Workflow 4: Device Authorization Grant
Device Auth Server User (Browser)
| | |
|--- Device AuthZ Request -->| |
|<-- device_code, | |
| user_code, | |
| verification_uri -------| |
| | |
|-- Display user_code ------>| |
| to user on screen | |
| |<-- User visits URI -----|
| |<-- Enters user_code ----|
| |<-- Authenticates -------|
| |<-- Consents ------------|
| | |
|--- Poll Token Endpoint --->| |
| (device_code) | |
|<-- Access Token -----------| |Workflow 5: Token Revocation
Steps:
1. Client sends revocation request: POST /revoke with token=xxx&token_type_hint=refresh_token 2. Auth server invalidates the token 3. If refresh token revoked, all associated access tokens also invalidated 4. Server returns 200 OK regardless of whether token was valid (prevents token fishing)
Workflow 6: Security Incident - Token Compromise Response
Steps:
1. Detect suspicious token usage (unusual IP, impossible travel) 2. Immediately revoke the compromised token via revocation endpoint 3. If refresh token compromised, revoke entire token family 4. Force re-authentication for affected user 5. Audit all API calls made with compromised token 6. Check for scope escalation attempts 7. Review authorization logs for the compromised session 8. Notify affected user and security team
#!/usr/bin/env python3
"""OAuth 2.0 authorization flow security audit agent."""
import json
import sys
import argparse
from datetime import datetime
try:
import requests
except ImportError:
print("Install: pip install requests")
sys.exit(1)
def discover_oauth_endpoints(issuer_url):
"""Discover OAuth 2.0 / OIDC endpoints from well-known configuration."""
discovery_url = f"{issuer_url.rstrip('/')}/.well-known/openid-configuration"
try:
resp = requests.get(discovery_url, timeout=10)
resp.raise_for_status()
config = resp.json()
return {
"issuer": config.get("issuer", ""),
"authorization_endpoint": config.get("authorization_endpoint", ""),
"token_endpoint": config.get("token_endpoint", ""),
"userinfo_endpoint": config.get("userinfo_endpoint", ""),
"jwks_uri": config.get("jwks_uri", ""),
"supported_grant_types": config.get("grant_types_supported", []),
"supported_scopes": config.get("scopes_supported", []),
"supported_response_types": config.get("response_types_supported", []),
"token_endpoint_auth_methods": config.get("token_endpoint_auth_methods_supported", []),
}
except Exception as e:
return {"error": str(e)}
def audit_oauth_security(config):
"""Audit OAuth configuration for security issues."""
findings = []
if "implicit" in config.get("supported_grant_types", []):
findings.append({
"issue": "Implicit grant type supported",
"severity": "HIGH",
"recommendation": "Disable implicit flow; use authorization code + PKCE",
})
if "password" in config.get("supported_grant_types", []):
findings.append({
"issue": "Resource owner password grant supported",
"severity": "MEDIUM",
"recommendation": "Disable ROPC grant; use authorization code flow",
})
auth_methods = config.get("token_endpoint_auth_methods", [])
if "none" in auth_methods:
findings.append({
"issue": "Token endpoint allows unauthenticated clients",
"severity": "MEDIUM",
"recommendation": "Require client_secret_basic or private_key_jwt",
})
if "code" in config.get("supported_response_types", []):
if "code id_token" not in config.get("supported_response_types", []):
findings.append({
"issue": "Authorization code flow available",
"severity": "INFO",
"note": "Ensure PKCE is enforced for public clients",
})
return findings
def test_token_endpoint(token_url, client_id, client_secret, grant_type="client_credentials"):
"""Test token endpoint with client credentials."""
try:
resp = requests.post(token_url, data={
"grant_type": grant_type,
"client_id": client_id,
"client_secret": client_secret,
}, timeout=10)
if resp.status_code == 200:
token_data = resp.json()
return {
"status": "success",
"token_type": token_data.get("token_type", ""),
"expires_in": token_data.get("expires_in", 0),
"scope": token_data.get("scope", ""),
}
return {"status": "failed", "code": resp.status_code, "body": resp.text[:200]}
except Exception as e:
return {"status": "error", "message": str(e)}
def run_audit(issuer_url, client_id=None, client_secret=None):
"""Execute OAuth 2.0 security audit."""
print(f"\n{'='*60}")
print(f" OAUTH 2.0 AUTHORIZATION FLOW AUDIT")
print(f" Issuer: {issuer_url}")
print(f" Generated: {datetime.utcnow().isoformat()} UTC")
print(f"{'='*60}\n")
config = discover_oauth_endpoints(issuer_url)
if "error" in config:
print(f" Error: {config['error']}")
return config
print(f"--- DISCOVERED ENDPOINTS ---")
print(f" Authorization: {config.get('authorization_endpoint', 'N/A')}")
print(f" Token: {config.get('token_endpoint', 'N/A')}")
print(f" JWKS: {config.get('jwks_uri', 'N/A')}")
print(f" Grant types: {config.get('supported_grant_types', [])}")
findings = audit_oauth_security(config)
print(f"\n--- SECURITY FINDINGS ({len(findings)}) ---")
for f in findings:
print(f" [{f['severity']}] {f['issue']}")
token_test = {}
if client_id and client_secret and config.get("token_endpoint"):
token_test = test_token_endpoint(config["token_endpoint"], client_id, client_secret)
print(f"\n--- TOKEN ENDPOINT TEST ---")
print(f" Status: {token_test.get('status', 'N/A')}")
return {"config": config, "findings": findings, "token_test": token_test}
def main():
parser = argparse.ArgumentParser(description="OAuth 2.0 Audit Agent")
parser.add_argument("--issuer", required=True, help="OAuth issuer URL")
parser.add_argument("--client-id", help="Client ID for token test")
parser.add_argument("--client-secret", help="Client secret for token test")
parser.add_argument("--output", help="Save report to JSON file")
args = parser.parse_args()
report = run_audit(args.issuer, args.client_id, args.client_secret)
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"\n[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
OAuth 2.0 Authorization Flow Security Auditor
Validates OAuth 2.0 configurations, tests PKCE implementation,
checks token security, and audits scope assignments for compliance
with OAuth 2.1 and RFC 9700 best practices.
"""
import hashlib
import base64
import secrets
import json
import time
import urllib.request
import urllib.error
import ssl
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass, field
@dataclass
class OAuthConfig:
"""OAuth 2.0 configuration to audit."""
authorization_endpoint: str
token_endpoint: str
revocation_endpoint: str = ""
userinfo_endpoint: str = ""
jwks_uri: str = ""
issuer: str = ""
client_id: str = ""
redirect_uris: List[str] = field(default_factory=list)
scopes_supported: List[str] = field(default_factory=list)
grant_types_supported: List[str] = field(default_factory=list)
response_types_supported: List[str] = field(default_factory=list)
pkce_required: bool = True
token_endpoint_auth_methods: List[str] = field(default_factory=list)
@dataclass
class AuditFinding:
"""Individual audit finding."""
category: str
severity: str # critical, high, medium, low, info
title: str
description: str
recommendation: str = ""
reference: str = ""
class PKCEHelper:
"""PKCE code verifier and challenge generation."""
@staticmethod
def generate_code_verifier(length: int = 128) -> str:
"""Generate a cryptographically random code verifier (43-128 chars)."""
if length < 43 or length > 128:
raise ValueError("Code verifier length must be between 43 and 128")
unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
return ''.join(secrets.choice(unreserved) for _ in range(length))
@staticmethod
def generate_code_challenge(code_verifier: str) -> str:
"""Compute S256 code challenge from code verifier."""
digest = hashlib.sha256(code_verifier.encode('ascii')).digest()
return base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
@staticmethod
def verify_pkce(code_verifier: str, code_challenge: str) -> bool:
"""Verify PKCE code_verifier matches code_challenge."""
computed = PKCEHelper.generate_code_challenge(code_verifier)
return secrets.compare_digest(computed, code_challenge)
@staticmethod
def generate_state() -> str:
"""Generate a cryptographically random state parameter."""
return secrets.token_urlsafe(32)
class OAuth2Auditor:
"""Audits OAuth 2.0 configurations against security best practices."""
DEPRECATED_GRANTS = ["implicit", "password"]
SECURE_AUTH_METHODS = [
"private_key_jwt",
"tls_client_auth",
"self_signed_tls_client_auth"
]
def __init__(self, config: OAuthConfig):
self.config = config
self.findings: List[AuditFinding] = []
def audit_all(self) -> List[AuditFinding]:
"""Run all OAuth 2.0 security audits."""
self.findings = []
self._audit_grant_types()
self._audit_pkce_requirement()
self._audit_redirect_uris()
self._audit_scopes()
self._audit_endpoints_https()
self._audit_token_endpoint_auth()
self._audit_response_types()
self._audit_revocation_endpoint()
self._audit_jwks_endpoint()
self._audit_discovery_endpoint()
return self.findings
def _audit_grant_types(self):
"""Check for deprecated or insecure grant types."""
for grant in self.config.grant_types_supported:
if grant in self.DEPRECATED_GRANTS:
self.findings.append(AuditFinding(
category="Grant Types",
severity="critical",
title=f"Deprecated grant type: {grant}",
description=f"The '{grant}' grant type is removed in OAuth 2.1 and is insecure.",
recommendation=f"Remove '{grant}' grant type. Use authorization_code with PKCE instead.",
reference="RFC 9700 Section 2.1"
))
if "authorization_code" not in self.config.grant_types_supported:
self.findings.append(AuditFinding(
category="Grant Types",
severity="high",
title="Authorization Code grant not supported",
description="The most secure interactive grant type is not enabled.",
recommendation="Enable authorization_code grant type with PKCE.",
reference="OAuth 2.1 Draft"
))
if "refresh_token" not in self.config.grant_types_supported:
self.findings.append(AuditFinding(
category="Grant Types",
severity="medium",
title="Refresh token grant not supported",
description="Without refresh tokens, users must re-authenticate more frequently or access tokens must have longer lifetimes.",
recommendation="Enable refresh_token grant with token rotation.",
reference="RFC 6749 Section 6"
))
if not any(g in self.DEPRECATED_GRANTS for g in self.config.grant_types_supported):
self.findings.append(AuditFinding(
category="Grant Types",
severity="info",
title="No deprecated grant types detected",
description="All configured grant types are aligned with OAuth 2.1 requirements."
))
def _audit_pkce_requirement(self):
"""Check if PKCE is required for authorization code flow."""
if "authorization_code" in self.config.grant_types_supported:
if self.config.pkce_required:
self.findings.append(AuditFinding(
category="PKCE",
severity="info",
title="PKCE is required for authorization code flow",
description="PKCE enforcement is correctly enabled, preventing code interception attacks."
))
else:
self.findings.append(AuditFinding(
category="PKCE",
severity="critical",
title="PKCE is not required",
description="Authorization code flow without PKCE is vulnerable to code interception attacks.",
recommendation="Enforce PKCE (code_challenge_method=S256) for all authorization code requests.",
reference="RFC 7636, OAuth 2.1 Draft"
))
def _audit_redirect_uris(self):
"""Check redirect URI security."""
for uri in self.config.redirect_uris:
if '*' in uri:
self.findings.append(AuditFinding(
category="Redirect URIs",
severity="critical",
title=f"Wildcard redirect URI: {uri}",
description="Wildcard redirect URIs enable open redirect attacks and token theft.",
recommendation="Use exact redirect URI matching. Register each URI explicitly.",
reference="RFC 9700 Section 4.1"
))
elif uri.startswith("http://") and "localhost" not in uri and "127.0.0.1" not in uri:
self.findings.append(AuditFinding(
category="Redirect URIs",
severity="high",
title=f"Non-HTTPS redirect URI: {uri}",
description="HTTP redirect URIs expose authorization codes in transit.",
recommendation="Use HTTPS for all production redirect URIs.",
reference="RFC 6749 Section 3.1.2.1"
))
elif uri.startswith("http://localhost") or uri.startswith("http://127.0.0.1"):
self.findings.append(AuditFinding(
category="Redirect URIs",
severity="low",
title=f"Localhost redirect URI: {uri}",
description="Localhost redirect URI detected. Acceptable for native apps per RFC 8252.",
reference="RFC 8252 Section 7.3"
))
if not self.config.redirect_uris:
self.findings.append(AuditFinding(
category="Redirect URIs",
severity="medium",
title="No redirect URIs configured for audit",
description="Could not audit redirect URIs - none provided in configuration."
))
def _audit_scopes(self):
"""Audit scope configuration for least privilege."""
overly_broad = ["*", "all", "admin", "root", "superuser"]
for scope in self.config.scopes_supported:
if scope.lower() in overly_broad:
self.findings.append(AuditFinding(
category="Scopes",
severity="high",
title=f"Overly broad scope: {scope}",
description="This scope grants excessive permissions violating least privilege.",
recommendation="Replace with granular scopes (e.g., read:users, write:orders).",
reference="NIST SP 800-53 AC-6"
))
if self.config.scopes_supported:
granular_pattern = any(':' in s or '.' in s for s in self.config.scopes_supported)
if not granular_pattern:
self.findings.append(AuditFinding(
category="Scopes",
severity="medium",
title="Scopes may lack granularity",
description="Scopes do not follow resource:action pattern (e.g., read:users).",
recommendation="Design scopes using resource:action notation for fine-grained access control."
))
def _audit_endpoints_https(self):
"""Verify all OAuth endpoints use HTTPS."""
endpoints = {
"Authorization": self.config.authorization_endpoint,
"Token": self.config.token_endpoint,
"Revocation": self.config.revocation_endpoint,
"UserInfo": self.config.userinfo_endpoint,
"JWKS": self.config.jwks_uri,
}
for name, url in endpoints.items():
if not url:
continue
if not url.startswith("https://"):
self.findings.append(AuditFinding(
category="Transport Security",
severity="critical",
title=f"{name} endpoint not using HTTPS",
description=f"{name} endpoint ({url}) is not secured with TLS.",
recommendation=f"Configure {name} endpoint to use HTTPS.",
reference="RFC 6749 Section 3.1"
))
def _audit_token_endpoint_auth(self):
"""Check token endpoint authentication methods."""
if not self.config.token_endpoint_auth_methods:
return
if "client_secret_post" in self.config.token_endpoint_auth_methods and \
"client_secret_basic" in self.config.token_endpoint_auth_methods:
self.findings.append(AuditFinding(
category="Client Authentication",
severity="medium",
title="Basic/POST client authentication supported",
description="client_secret_basic and client_secret_post transmit secrets in requests.",
recommendation="Prefer private_key_jwt or tls_client_auth for higher assurance.",
reference="RFC 9700"
))
has_secure = any(m in self.SECURE_AUTH_METHODS for m in self.config.token_endpoint_auth_methods)
if has_secure:
self.findings.append(AuditFinding(
category="Client Authentication",
severity="info",
title="Strong client authentication methods available",
description="Server supports certificate-based or JWT-based client authentication."
))
if "none" in self.config.token_endpoint_auth_methods:
self.findings.append(AuditFinding(
category="Client Authentication",
severity="high",
title="Unauthenticated token endpoint access allowed",
description="Token endpoint accepts requests without client authentication.",
recommendation="Require PKCE for public clients and client authentication for confidential clients."
))
def _audit_response_types(self):
"""Check for insecure response types."""
insecure_types = ["token", "id_token"]
for rt in self.config.response_types_supported:
if rt in insecure_types:
self.findings.append(AuditFinding(
category="Response Types",
severity="high",
title=f"Implicit response type enabled: {rt}",
description=f"Response type '{rt}' exposes tokens in browser URL/history.",
recommendation="Use 'code' response type with PKCE instead.",
reference="OAuth 2.1 Draft, RFC 9700"
))
def _audit_revocation_endpoint(self):
"""Check if token revocation endpoint is configured."""
if not self.config.revocation_endpoint:
self.findings.append(AuditFinding(
category="Token Revocation",
severity="high",
title="No token revocation endpoint configured",
description="Without revocation, compromised tokens cannot be invalidated before expiry.",
recommendation="Implement RFC 7009 token revocation endpoint.",
reference="RFC 7009"
))
def _audit_jwks_endpoint(self):
"""Check JWKS endpoint availability for token verification."""
if not self.config.jwks_uri:
self.findings.append(AuditFinding(
category="Token Verification",
severity="medium",
title="No JWKS URI configured",
description="Resource servers need JWKS endpoint to verify JWT signatures.",
recommendation="Publish JWKS endpoint for token signature verification."
))
def _audit_discovery_endpoint(self):
"""Check OpenID Connect Discovery metadata."""
if not self.config.issuer:
return
discovery_url = f"{self.config.issuer.rstrip('/')}/.well-known/openid-configuration"
try:
req = urllib.request.Request(
discovery_url,
headers={'User-Agent': 'OAuth2-Auditor/1.0'}
)
ctx = ssl.create_default_context()
response = urllib.request.urlopen(req, context=ctx, timeout=10)
if response.status == 200:
metadata = json.loads(response.read().decode('utf-8'))
self.findings.append(AuditFinding(
category="Discovery",
severity="info",
title="OpenID Connect Discovery endpoint accessible",
description=f"Discovery metadata available at {discovery_url}"
))
# Check for PKCE support in discovery
if "code_challenge_methods_supported" in metadata:
methods = metadata["code_challenge_methods_supported"]
if "S256" in methods:
self.findings.append(AuditFinding(
category="PKCE",
severity="info",
title="S256 PKCE method supported",
description="Server advertises S256 code challenge method support."
))
if "plain" in methods:
self.findings.append(AuditFinding(
category="PKCE",
severity="high",
title="Plain PKCE method supported",
description="'plain' code challenge method does not provide security.",
recommendation="Require S256 only. Disable plain method.",
reference="RFC 7636 Section 4.2"
))
except Exception as e:
self.findings.append(AuditFinding(
category="Discovery",
severity="low",
title="Cannot reach discovery endpoint",
description=f"Error accessing {discovery_url}: {str(e)}"
))
def generate_report(self) -> str:
"""Generate audit report."""
if not self.findings:
self.audit_all()
severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4}
sorted_findings = sorted(self.findings, key=lambda f: severity_order.get(f.severity, 5))
lines = [
"=" * 70,
"OAUTH 2.0 SECURITY AUDIT REPORT",
"=" * 70,
f"Issuer: {self.config.issuer or 'N/A'}",
f"Authorization Endpoint: {self.config.authorization_endpoint}",
f"Token Endpoint: {self.config.token_endpoint}",
f"Grant Types: {', '.join(self.config.grant_types_supported)}",
f"PKCE Required: {self.config.pkce_required}",
"-" * 70,
""
]
by_severity = {}
for f in sorted_findings:
by_severity.setdefault(f.severity, []).append(f)
total = len(self.findings)
critical = len(by_severity.get("critical", []))
high = len(by_severity.get("high", []))
lines.append(f"TOTAL FINDINGS: {total}")
lines.append(f" Critical: {critical} | High: {high} | Medium: {len(by_severity.get('medium', []))} | Low: {len(by_severity.get('low', []))} | Info: {len(by_severity.get('info', []))}")
lines.append("")
for f in sorted_findings:
icon = {"critical": "[!!!]", "high": "[!!]", "medium": "[!]", "low": "[~]", "info": "[i]"}.get(f.severity, "[?]")
lines.append(f"{icon} [{f.severity.upper()}] {f.title}")
lines.append(f" Category: {f.category}")
lines.append(f" {f.description}")
if f.recommendation:
lines.append(f" Recommendation: {f.recommendation}")
if f.reference:
lines.append(f" Reference: {f.reference}")
lines.append("")
overall = "FAIL" if critical > 0 else "NEEDS IMPROVEMENT" if high > 0 else "PASS"
lines.append("=" * 70)
lines.append(f"OVERALL: {overall}")
lines.append("=" * 70)
return "\n".join(lines)
def main():
"""Run OAuth 2.0 security audit with example configuration."""
config = OAuthConfig(
authorization_endpoint="https://auth.example.com/authorize",
token_endpoint="https://auth.example.com/oauth/token",
revocation_endpoint="https://auth.example.com/oauth/revoke",
userinfo_endpoint="https://auth.example.com/userinfo",
jwks_uri="https://auth.example.com/.well-known/jwks.json",
issuer="https://auth.example.com",
client_id="my-app-client",
redirect_uris=[
"https://app.example.com/callback",
"http://localhost:3000/callback"
],
scopes_supported=["openid", "profile", "email", "read:users", "write:users"],
grant_types_supported=["authorization_code", "refresh_token", "client_credentials"],
response_types_supported=["code"],
pkce_required=True,
token_endpoint_auth_methods=["client_secret_basic", "private_key_jwt"]
)
auditor = OAuth2Auditor(config)
report = auditor.generate_report()
print(report)
# Demo PKCE generation
print("\n--- PKCE Demo ---")
verifier = PKCEHelper.generate_code_verifier(128)
challenge = PKCEHelper.generate_code_challenge(verifier)
state = PKCEHelper.generate_state()
print(f"Code Verifier: {verifier[:40]}...")
print(f"Code Challenge (S256): {challenge}")
print(f"State: {state}")
print(f"Verification: {PKCEHelper.verify_pkce(verifier, challenge)}")
if __name__ == "__main__":
main()