Skip to content

OAuth2 Security — CSRF, Code Injection, and Best Practices

DodaTech Updated 2026-06-28 3 min read

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

  1. What does the state parameter protect against?
  2. What does PKCE protect against?
  3. Why must redirect URIs be strictly validated?
  4. Why is HTTPS required for all OAuth2 endpoints?
  5. How does short token TTL improve security?

Answers:

  1. CSRF attacks — prevents an attacker from swapping the authorization code.
  2. Authorization code interception — prevents an attacker with the code from exchanging it for tokens.
  3. Without strict validation, an attacker can use an open redirector on the legitimate domain to intercept codes.
  4. Without HTTPS, tokens, codes, and credentials can be intercepted in transit by anyone on the network.
  5. 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

Is OAuth2 secure by default?

No. Security depends on correct implementation of state, PKCE, redirect URI validation, and HTTPS. Missing any of these creates vulnerabilities.

What is the most common OAuth2 vulnerability?

Missing state parameter (CSRF) and weak redirect URI validation. Both are common in custom OAuth2 implementations.

Does PKCE make state unnecessary?

No. PKCE prevents code interception. State prevents CSRF. Both are needed.

Can OAuth2 be used without HTTPS?

No. OAuth2 Security BCP requires HTTPS for all endpoints. Tokens and credentials must be encrypted in transit.

What is the OAuth2 Security BCP?

RFC 9700 — Best Current Practice for OAuth 2.0. It recommends PKCE for all clients, deprecates Implicit grant, and requires HTTPS.

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