OAuth2 Security — CSRF, Code Injection, and Best Practices
In this tutorial, you will learn about OAuth2 Security. We cover key concepts, practical examples, and best practices to help you master this topic.
OAuth2 security relies on multiple mechanisms working together: state parameter, PKCE, redirect URI validation, and HTTPS. Each addresses a specific attack vector.
What You'll Learn
The main OAuth2 security mechanisms, how they prevent specific attacks, and common misconfigurations that create vulnerabilities.
Why It Matters
OAuth2 is inherently secure when implemented correctly. However, each component (state, PKCE, redirect URIs) must be properly configured. Missing one mechanism leaves a gap attackers can exploit.
Real-World Use
Google's OAuth2 implementation requires state, supports PKCE, validates redirect URIs strictly, and requires HTTPS. These mechanisms together protect billions of authorizations daily.
flowchart TD
A["OAuth2 Security"] --> B["State Parameter\nPrevents CSRF"]
A --> C["PKCE\nPrevents Code Interception"]
A --> D["Redirect URI Validation\nPrevents Open Redirectors"]
A --> E["HTTPS\nEncrypts All Traffic"]
A --> F["Client Authentication\nVerifies Client Identity"]
A --> G["Short-Lived Tokens\nLimits Damage Window"]
style A fill:#dbeafe,stroke:#2563eb
style B fill:#dcfce7,stroke:#16a34a
style C fill:#dcfce7,stroke:#16a34a
style D fill:#dcfce7,stroke:#16a34a
style E fill:#dcfce7,stroke:#16a34a
style F fill:#fef3c7,stroke:#d97706
style G fill:#dcfce7,stroke:#16a34a
Security Mechanisms
| Mechanism | Protects Against |
|---|---|
| State parameter | CSRF Attacks on the authorization code |
| PKCE | Authorization code interception |
| Redirect URI validation | Open redirector attacks |
| HTTPS | Token interception in transit |
| Client authentication | Token issuance to unauthorized clients |
| Short token TTL | Token misuse if stolen |
Code Injection Attack
An attacker injects a malicious authorization code by exploiting missing state validation:
# VULNERABLE — no state validation
@app.route("/callback")
def callback():
code = request.args.get("code")
# Attacker can inject their own code here
tokens = exchange_code(code)
return jsonify(tokens)
How to fix:
# SECURE — validate state parameter
@app.route("/callback")
def callback():
code = request.args.get("code")
state = request.args.get("state")
if state != session.get("oauth_state"):
return "CSRF detected", 400
tokens = exchange_code(code)
return jsonify(tokens)
Common Mistakes
1. Missing State Parameter
Without state, CSRF attacks can swap the authorization code. Always use state.
2. Using HTTP Instead of HTTPS
Without HTTPS, tokens can be intercepted on the network. Every endpoint must use HTTPS.
3. Weak Redirect URI Validation
Wildcard redirect URIs (https://*.ngrok.io/*) allow attackers to register their own subdomains.
4. Not Rotating Client Secrets
If a client secret is compromised, rotation limits the window of opportunity.
5. Long-Lived Authorization Codes
Codes should expire within 1-2 minutes. Long-lived codes can be intercepted and exchanged later.
Practice Questions
- What does the state parameter protect against?
- What does PKCE protect against?
- Why must redirect URIs be strictly validated?
- Why is HTTPS required for all OAuth2 endpoints?
- How does short token TTL improve security?
Answers:
- CSRF attacks — prevents an attacker from swapping the authorization code.
- Authorization code interception — prevents an attacker with the code from exchanging it for tokens.
- Without strict validation, an attacker can use an open redirector on the legitimate domain to intercept codes.
- Without HTTPS, tokens, codes, and credentials can be intercepted in transit by anyone on the network.
- Short TTL limits the window during which a stolen token can be used.
Challenge: Perform a security audit of an OAuth2 implementation. Check for state parameter usage, PKCE, redirect URI validation, HTTPS, and token TTL. Document any vulnerabilities.
FAQ
Mini Project
Create an OAuth2 security checklist and test script. The script should check a provider's authorization endpoint for: state requirement, PKCE support, HTTPS enforcement, redirect URI validation, and code expiry.
What's Next
Now learn about OAuth2 Attacks — specific attack vectors and how to defend against them.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro