mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
842 lines
39 KiB
HTML
842 lines
39 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>security-oauth2-implementation</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/security-oauth2-implementation.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/security-oauth2-implementation">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/security-oauth2-implementation.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>security-oauth2-implementation</h1><p class="lede">OAuth 2.0 implementation including authorization code, client credentials, PKCE, refresh tokens, and security best practices</p><h1>Security: OAuth 2.0 Implementation</h1>
|
|
<p><strong>Scope</strong>: OAuth 2.0 flows, PKCE, token management, authorization server setup <strong>Lines</strong>: ~400 <strong>Last Updated</strong>: 2025-10-27</p>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Implementing OAuth 2.0 authorization server</li><li>Adding OAuth 2.0 to client applications</li><li>Securing APIs with OAuth 2.0 tokens</li><li>Implementing authorization code flow with PKCE</li><li>Setting up service-to-service authentication (client credentials)</li><li>Implementing refresh token rotation</li><li>Migrating from session-based to token-based auth</li><li>Integrating with third-party OAuth providers</li></ul>
|
|
<h2>OAuth 2.0 Fundamentals</h2>
|
|
<h3>Roles</h3>
|
|
<pre><code class="lang-python">"""
|
|
OAuth 2.0 Four Roles:
|
|
|
|
1. Resource Owner (User)
|
|
- Owns the protected data
|
|
- Grants access to client applications
|
|
|
|
2. Client (Application)
|
|
- Requests access to protected resources
|
|
- Types: Confidential (server-side) or Public (mobile/SPA)
|
|
|
|
3. Authorization Server
|
|
- Authenticates resource owner
|
|
- Issues access tokens to clients
|
|
|
|
4. Resource Server (API)
|
|
- Hosts protected resources
|
|
- Validates access tokens
|
|
"""</code></pre>
|
|
<h3>Grant Types</h3>
|
|
<h4>1. Authorization Code Flow (Most Secure)</h4>
|
|
<p><strong>Use for</strong>: Web applications with server-side backend</p>
|
|
<pre><code class="lang-python">"""
|
|
Flow:
|
|
1. Client redirects user to authorization server
|
|
2. User authenticates and authorizes
|
|
3. Authorization server redirects back with code
|
|
4. Client exchanges code for tokens (server-side)
|
|
5. Client uses access token to call API
|
|
|
|
Security: Code never exposed to browser, client secret required
|
|
"""
|
|
|
|
from flask import Flask, redirect, request, session
|
|
import requests
|
|
import secrets
|
|
|
|
app = Flask(__name__)
|
|
app.secret_key = secrets.token_hex(32)
|
|
|
|
AUTH_SERVER = "https://auth.example.com"
|
|
CLIENT_ID = "your-client-id"
|
|
CLIENT_SECRET = "your-client-secret"
|
|
REDIRECT_URI = "https://yourapp.com/callback"
|
|
|
|
@app.route('/login')
|
|
def login():
|
|
"""Initiate authorization code flow"""
|
|
|
|
# Generate state for CSRF protection
|
|
state = secrets.token_urlsafe(32)
|
|
session['oauth_state'] = state
|
|
|
|
# Build authorization URL
|
|
params = {
|
|
'response_type': 'code',
|
|
'client_id': CLIENT_ID,
|
|
'redirect_uri': REDIRECT_URI,
|
|
'scope': 'read write',
|
|
'state': state
|
|
}
|
|
|
|
auth_url = f"{AUTH_SERVER}/authorize?" + "&".join(
|
|
f"{k}={v}" for k, v in params.items()
|
|
)
|
|
|
|
return redirect(auth_url)
|
|
|
|
@app.route('/callback')
|
|
def callback():
|
|
"""Handle authorization callback"""
|
|
|
|
# Validate state (CSRF protection)
|
|
if request.args.get('state') != session.get('oauth_state'):
|
|
return "Invalid state", 400
|
|
|
|
# Get authorization code
|
|
code = request.args.get('code')
|
|
if not code:
|
|
error = request.args.get('error')
|
|
return f"Authorization failed: {error}", 400
|
|
|
|
# Exchange code for tokens
|
|
token_response = requests.post(
|
|
f"{AUTH_SERVER}/token",
|
|
data={
|
|
'grant_type': 'authorization_code',
|
|
'code': code,
|
|
'redirect_uri': REDIRECT_URI,
|
|
'client_id': CLIENT_ID,
|
|
'client_secret': CLIENT_SECRET
|
|
}
|
|
)
|
|
|
|
if token_response.status_code != 200:
|
|
return "Token exchange failed", 500
|
|
|
|
tokens = token_response.json()
|
|
|
|
# Store tokens securely
|
|
session['access_token'] = tokens['access_token']
|
|
session['refresh_token'] = tokens.get('refresh_token')
|
|
|
|
return redirect('/dashboard')</code></pre>
|
|
<h4>2. Authorization Code Flow with PKCE</h4>
|
|
<p><strong>Use for</strong>: Mobile apps, SPAs, any public client</p>
|
|
<pre><code class="lang-python">"""
|
|
PKCE (Proof Key for Code Exchange) - RFC 7636
|
|
Prevents authorization code interception attacks
|
|
|
|
Additional steps:
|
|
1. Client generates code_verifier (random string)
|
|
2. Client creates code_challenge = SHA256(code_verifier)
|
|
3. Authorization request includes code_challenge
|
|
4. Token request includes code_verifier
|
|
5. Server validates: SHA256(code_verifier) == code_challenge
|
|
"""
|
|
|
|
import secrets
|
|
import hashlib
|
|
import base64
|
|
|
|
def generate_pkce_pair():
|
|
"""Generate PKCE code verifier and challenge"""
|
|
|
|
# Generate code verifier (43-128 chars)
|
|
code_verifier = secrets.token_urlsafe(64) # 86 chars
|
|
|
|
# Create code challenge (S256 method)
|
|
challenge_bytes = hashlib.sha256(code_verifier.encode()).digest()
|
|
code_challenge = base64.urlsafe_b64encode(challenge_bytes).decode().rstrip('=')
|
|
|
|
return code_verifier, code_challenge
|
|
|
|
# Client initiates flow
|
|
code_verifier, code_challenge = generate_pkce_pair()
|
|
|
|
# Step 1: Authorization request with challenge
|
|
auth_params = {
|
|
'response_type': 'code',
|
|
'client_id': CLIENT_ID,
|
|
'redirect_uri': REDIRECT_URI,
|
|
'scope': 'read write',
|
|
'state': state,
|
|
'code_challenge': code_challenge,
|
|
'code_challenge_method': 'S256' # SHA-256
|
|
}
|
|
|
|
# Step 2: Token request with verifier
|
|
token_data = {
|
|
'grant_type': 'authorization_code',
|
|
'code': authorization_code,
|
|
'redirect_uri': REDIRECT_URI,
|
|
'client_id': CLIENT_ID,
|
|
'code_verifier': code_verifier # Server validates this
|
|
}</code></pre>
|
|
<h4>3. Client Credentials Flow</h4>
|
|
<p><strong>Use for</strong>: Server-to-server authentication, no user involved</p>
|
|
<pre><code class="lang-python">"""
|
|
Flow:
|
|
1. Client sends credentials to token endpoint
|
|
2. Authorization server validates and issues token
|
|
3. Client uses token to access API
|
|
|
|
No user interaction - machine-to-machine
|
|
"""
|
|
|
|
import requests
|
|
from requests.auth import HTTPBasicAuth
|
|
|
|
def get_access_token(client_id: str, client_secret: str, scope: str = None):
|
|
"""Get access token using client credentials"""
|
|
|
|
response = requests.post(
|
|
f"{AUTH_SERVER}/token",
|
|
auth=HTTPBasicAuth(client_id, client_secret),
|
|
data={
|
|
'grant_type': 'client_credentials',
|
|
'scope': scope or 'api:read api:write'
|
|
}
|
|
)
|
|
|
|
response.raise_for_status()
|
|
return response.json()['access_token']
|
|
|
|
# Usage
|
|
token = get_access_token(CLIENT_ID, CLIENT_SECRET)
|
|
|
|
# Use token for API calls
|
|
api_response = requests.get(
|
|
"https://api.example.com/resource",
|
|
headers={'Authorization': f'Bearer {token}'}
|
|
)</code></pre>
|
|
<h4>4. Refresh Token Flow</h4>
|
|
<p><strong>Use for</strong>: Obtaining new access token without re-authentication</p>
|
|
<pre><code class="lang-python">"""
|
|
Refresh Token Strategy:
|
|
- Access tokens: Short-lived (5-15 minutes)
|
|
- Refresh tokens: Long-lived (days/weeks/months)
|
|
- Use refresh token to get new access token
|
|
- Implement refresh token rotation for security
|
|
"""
|
|
|
|
def refresh_access_token(refresh_token: str):
|
|
"""Exchange refresh token for new access token"""
|
|
|
|
response = requests.post(
|
|
f"{AUTH_SERVER}/token",
|
|
data={
|
|
'grant_type': 'refresh_token',
|
|
'refresh_token': refresh_token,
|
|
'client_id': CLIENT_ID,
|
|
'client_secret': CLIENT_SECRET
|
|
}
|
|
)
|
|
|
|
if response.status_code != 200:
|
|
# Refresh token invalid/expired - user must re-authenticate
|
|
return None
|
|
|
|
tokens = response.json()
|
|
|
|
return {
|
|
'access_token': tokens['access_token'],
|
|
'refresh_token': tokens.get('refresh_token'), # May rotate
|
|
'expires_in': tokens['expires_in']
|
|
}
|
|
|
|
# Automatic token refresh wrapper
|
|
class OAuth2Client:
|
|
"""OAuth 2.0 client with automatic token refresh"""
|
|
|
|
def __init__(self, access_token, refresh_token, expires_at):
|
|
self.access_token = access_token
|
|
self.refresh_token = refresh_token
|
|
self.expires_at = expires_at
|
|
|
|
def get_valid_token(self):
|
|
"""Get access token, refreshing if needed"""
|
|
import time
|
|
|
|
if time.time() >= self.expires_at - 60: # Refresh 1 min early
|
|
tokens = refresh_access_token(self.refresh_token)
|
|
|
|
if not tokens:
|
|
raise Exception("Refresh token expired")
|
|
|
|
self.access_token = tokens['access_token']
|
|
self.refresh_token = tokens['refresh_token']
|
|
self.expires_at = time.time() + tokens['expires_in']
|
|
|
|
return self.access_token
|
|
|
|
def api_call(self, url, **kwargs):
|
|
"""Make API call with automatic token refresh"""
|
|
token = self.get_valid_token()
|
|
|
|
headers = kwargs.get('headers', {})
|
|
headers['Authorization'] = f'Bearer {token}'
|
|
kwargs['headers'] = headers
|
|
|
|
return requests.get(url, **kwargs)</code></pre>
|
|
<h2>Authorization Server Implementation</h2>
|
|
<h3>Simple Authorization Server (Python)</h3>
|
|
<pre><code class="lang-python">from flask import Flask, request, jsonify, redirect
|
|
from datetime import datetime, timedelta
|
|
import secrets
|
|
import hashlib
|
|
import sqlite3
|
|
|
|
app = Flask(__name__)
|
|
|
|
class AuthorizationServer:
|
|
"""Minimal OAuth 2.0 authorization server"""
|
|
|
|
def __init__(self):
|
|
self.codes = {} # {code: {client_id, redirect_uri, user_id, code_challenge}}
|
|
self.tokens = {} # {token: {user_id, client_id, scope, expires}}
|
|
self.clients = {
|
|
'client123': {
|
|
'secret': 'secret456',
|
|
'redirect_uris': ['https://client.example.com/callback']
|
|
}
|
|
}
|
|
|
|
def validate_client(self, client_id, client_secret=None):
|
|
"""Validate client credentials"""
|
|
if client_id not in self.clients:
|
|
return False
|
|
|
|
if client_secret:
|
|
return self.clients[client_id]['secret'] == client_secret
|
|
|
|
return True
|
|
|
|
def validate_redirect_uri(self, client_id, redirect_uri):
|
|
"""Validate redirect URI (exact match)"""
|
|
allowed = self.clients[client_id]['redirect_uris']
|
|
return redirect_uri in allowed
|
|
|
|
def generate_authorization_code(self, client_id, redirect_uri, user_id,
|
|
code_challenge=None):
|
|
"""Generate authorization code"""
|
|
code = secrets.token_urlsafe(32)
|
|
|
|
self.codes[code] = {
|
|
'client_id': client_id,
|
|
'redirect_uri': redirect_uri,
|
|
'user_id': user_id,
|
|
'code_challenge': code_challenge,
|
|
'expires': datetime.now() + timedelta(minutes=10)
|
|
}
|
|
|
|
return code
|
|
|
|
def verify_pkce(self, code_verifier, code_challenge):
|
|
"""Verify PKCE code challenge"""
|
|
# S256: BASE64URL(SHA256(code_verifier)) == code_challenge
|
|
challenge_bytes = hashlib.sha256(code_verifier.encode()).digest()
|
|
computed_challenge = base64.urlsafe_b64encode(challenge_bytes).decode().rstrip('=')
|
|
|
|
return computed_challenge == code_challenge
|
|
|
|
def generate_token(self, user_id, client_id, scope):
|
|
"""Generate access token"""
|
|
token = secrets.token_urlsafe(32)
|
|
|
|
self.tokens[token] = {
|
|
'user_id': user_id,
|
|
'client_id': client_id,
|
|
'scope': scope,
|
|
'expires': datetime.now() + timedelta(hours=1)
|
|
}
|
|
|
|
return token
|
|
|
|
auth_server = AuthorizationServer()
|
|
|
|
@app.route('/authorize')
|
|
def authorize():
|
|
"""Authorization endpoint"""
|
|
|
|
# Validate parameters
|
|
response_type = request.args.get('response_type')
|
|
client_id = request.args.get('client_id')
|
|
redirect_uri = request.args.get('redirect_uri')
|
|
state = request.args.get('state')
|
|
code_challenge = request.args.get('code_challenge')
|
|
|
|
# Validate client
|
|
if not auth_server.validate_client(client_id):
|
|
return "Invalid client", 400
|
|
|
|
# Validate redirect URI
|
|
if not auth_server.validate_redirect_uri(client_id, redirect_uri):
|
|
return "Invalid redirect URI", 400
|
|
|
|
# Validate response type
|
|
if response_type != 'code':
|
|
return redirect(f"{redirect_uri}?error=unsupported_response_type&state={state}")
|
|
|
|
# TODO: Authenticate user and get consent
|
|
user_id = "user123" # From session after login
|
|
|
|
# Generate authorization code
|
|
code = auth_server.generate_authorization_code(
|
|
client_id, redirect_uri, user_id, code_challenge
|
|
)
|
|
|
|
# Redirect back to client
|
|
callback_url = f"{redirect_uri}?code={code}"
|
|
if state:
|
|
callback_url += f"&state={state}"
|
|
|
|
return redirect(callback_url)
|
|
|
|
@app.route('/token', methods=['POST'])
|
|
def token():
|
|
"""Token endpoint"""
|
|
|
|
grant_type = request.form.get('grant_type')
|
|
|
|
if grant_type == 'authorization_code':
|
|
return handle_authorization_code_grant()
|
|
elif grant_type == 'client_credentials':
|
|
return handle_client_credentials_grant()
|
|
elif grant_type == 'refresh_token':
|
|
return handle_refresh_token_grant()
|
|
else:
|
|
return jsonify({'error': 'unsupported_grant_type'}), 400
|
|
|
|
def handle_authorization_code_grant():
|
|
"""Handle authorization code grant"""
|
|
|
|
code = request.form.get('code')
|
|
redirect_uri = request.form.get('redirect_uri')
|
|
client_id = request.form.get('client_id')
|
|
client_secret = request.form.get('client_secret')
|
|
code_verifier = request.form.get('code_verifier')
|
|
|
|
# Validate client
|
|
if not auth_server.validate_client(client_id, client_secret):
|
|
return jsonify({'error': 'invalid_client'}), 401
|
|
|
|
# Validate code
|
|
if code not in auth_server.codes:
|
|
return jsonify({'error': 'invalid_grant'}), 400
|
|
|
|
code_data = auth_server.codes[code]
|
|
|
|
# Check expiration
|
|
if datetime.now() > code_data['expires']:
|
|
del auth_server.codes[code]
|
|
return jsonify({'error': 'invalid_grant'}), 400
|
|
|
|
# Validate redirect URI
|
|
if code_data['redirect_uri'] != redirect_uri:
|
|
return jsonify({'error': 'invalid_grant'}), 400
|
|
|
|
# Validate PKCE if used
|
|
if code_data['code_challenge']:
|
|
if not code_verifier:
|
|
return jsonify({'error': 'invalid_request'}), 400
|
|
|
|
if not auth_server.verify_pkce(code_verifier, code_data['code_challenge']):
|
|
return jsonify({'error': 'invalid_grant'}), 400
|
|
|
|
# Generate tokens
|
|
access_token = auth_server.generate_token(
|
|
code_data['user_id'], client_id, 'read write'
|
|
)
|
|
refresh_token = secrets.token_urlsafe(32)
|
|
|
|
# Delete used code (single use)
|
|
del auth_server.codes[code]
|
|
|
|
return jsonify({
|
|
'access_token': access_token,
|
|
'token_type': 'Bearer',
|
|
'expires_in': 3600,
|
|
'refresh_token': refresh_token
|
|
})</code></pre>
|
|
<h2>Token Validation</h2>
|
|
<h3>Resource Server Token Validation</h3>
|
|
<pre><code class="lang-python">from functools import wraps
|
|
from flask import request, jsonify
|
|
import jwt
|
|
|
|
def require_oauth(scope_required=None):
|
|
"""Decorator to protect endpoints with OAuth"""
|
|
|
|
def decorator(f):
|
|
@wraps(f)
|
|
def decorated_function(*args, **kwargs):
|
|
# Extract token from header
|
|
auth_header = request.headers.get('Authorization')
|
|
|
|
if not auth_header or not auth_header.startswith('Bearer '):
|
|
return jsonify({'error': 'missing_token'}), 401
|
|
|
|
token = auth_header[7:] # Remove 'Bearer '
|
|
|
|
# Validate token
|
|
try:
|
|
# Option 1: JWT validation (if using JWTs)
|
|
payload = jwt.decode(
|
|
token,
|
|
PUBLIC_KEY,
|
|
algorithms=['RS256'],
|
|
audience='https://api.example.com'
|
|
)
|
|
|
|
# Option 2: Token introspection (opaque tokens)
|
|
# payload = introspect_token(token)
|
|
|
|
except jwt.ExpiredSignatureError:
|
|
return jsonify({'error': 'token_expired'}), 401
|
|
except jwt.InvalidTokenError:
|
|
return jsonify({'error': 'invalid_token'}), 401
|
|
|
|
# Validate scope
|
|
if scope_required:
|
|
token_scopes = payload.get('scope', '').split()
|
|
if scope_required not in token_scopes:
|
|
return jsonify({'error': 'insufficient_scope'}), 403
|
|
|
|
# Add user info to request context
|
|
request.oauth_user_id = payload.get('sub')
|
|
request.oauth_scope = payload.get('scope')
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
return decorated_function
|
|
return decorator
|
|
|
|
# Usage
|
|
@app.route('/api/protected')
|
|
@require_oauth(scope_required='read')
|
|
def protected_endpoint():
|
|
user_id = request.oauth_user_id
|
|
return jsonify({'user_id': user_id, 'data': 'sensitive'})</code></pre>
|
|
<h2>Security Best Practices</h2>
|
|
<h3>OAuth 2.0 Security Checklist</h3>
|
|
<pre><code class="lang-python">"""
|
|
CRITICAL Security Requirements:
|
|
|
|
1. Always use HTTPS (TLS 1.2+)
|
|
- Never send tokens/codes over HTTP
|
|
- Use HSTS headers
|
|
|
|
2. Validate redirect URIs (EXACT match)
|
|
- No wildcards or pattern matching
|
|
- Store allowed URIs in database
|
|
|
|
3. Use state parameter (CSRF protection)
|
|
- Generate random state for each request
|
|
- Validate in callback
|
|
|
|
4. Implement PKCE for ALL clients
|
|
- Mandatory for public clients (mobile/SPA)
|
|
- Recommended for confidential clients
|
|
|
|
5. Short-lived access tokens
|
|
- 5-15 minutes maximum
|
|
- Use refresh tokens for longevity
|
|
|
|
6. Refresh token rotation
|
|
- Issue new refresh token on use
|
|
- Revoke old refresh token
|
|
- Detect token theft (family tracking)
|
|
|
|
7. Token storage
|
|
- Hash refresh tokens in database (SHA-256)
|
|
- Never store tokens in localStorage (XSS risk)
|
|
- Use httpOnly cookies or secure storage
|
|
|
|
8. Client authentication
|
|
- Require client_secret for confidential clients
|
|
- Validate credentials on every request
|
|
|
|
9. Rate limiting
|
|
- Limit token requests per client
|
|
- Detect brute force attacks
|
|
|
|
10. Scope validation
|
|
- Validate requested scopes
|
|
- Enforce least privilege
|
|
- Check scopes on resource access
|
|
"""</code></pre>
|
|
<h3>Common Vulnerabilities</h3>
|
|
<pre><code class="lang-python">"""
|
|
Common OAuth 2.0 Vulnerabilities:
|
|
|
|
1. Authorization Code Interception
|
|
Attack: Intercept code in redirect
|
|
Mitigation: PKCE
|
|
|
|
2. Redirect URI Manipulation
|
|
Attack: Change redirect_uri to attacker domain
|
|
Mitigation: Exact URI matching
|
|
|
|
3. State Parameter Missing
|
|
Attack: CSRF on OAuth flow
|
|
Mitigation: Always use state parameter
|
|
|
|
4. Token Leakage
|
|
Attack: Tokens in URLs, logs, referrer
|
|
Mitigation: Use POST for tokens, no tokens in URLs
|
|
|
|
5. Insufficient Redirect URI Validation
|
|
Attack: Open redirect to steal codes
|
|
Mitigation: Strict whitelist validation
|
|
|
|
6. Refresh Token Reuse
|
|
Attack: Stolen refresh token used indefinitely
|
|
Mitigation: Token rotation, family tracking
|
|
|
|
7. Scope Escalation
|
|
Attack: Request excessive scopes
|
|
Mitigation: User consent, scope validation
|
|
"""</code></pre>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><code>security-authentication.md</code> - Authentication patterns, JWT, sessions</li><li><code>api-authentication.md</code> - API authentication strategies</li><li><code>security-secrets-management.md</code> - Storing client secrets, tokens</li><li><code>api-rest-design.md</code> - RESTful API design with OAuth</li></ul>
|
|
<h2>Level 3: Resources</h2>
|
|
<h3>Comprehensive Reference</h3>
|
|
<p><strong>Location</strong>: <code>skills/security/oauth2-implementation/resources/REFERENCE.md</code></p>
|
|
<p>The REFERENCE.md file (3,200+ lines) provides exhaustive coverage of:</p>
|
|
<ul><li>Complete OAuth 2.0 specification (RFC 6749) with all grant types</li><li>Authorization code flow with detailed sequence diagrams</li><li>Client credentials flow for machine-to-machine authentication</li><li>Device authorization flow (RFC 8628) for limited-input devices</li><li>PKCE specification (RFC 7636) with S256 and plain methods</li><li>Refresh token rotation and family tracking</li><li>Token introspection (RFC 7662) and revocation (RFC 7009)</li><li>Scope design best practices and hierarchies</li><li>Security considerations from RFC 6819</li><li>OAuth 2.1 draft updates and deprecations</li><li>JWT vs opaque tokens comparison</li><li>Authorization server implementation patterns</li><li>Client libraries for Python, Node.js, Go, Java</li><li>Integration with Keycloak, Auth0, Okta, ORY Hydra</li><li>OpenID Connect (OIDC) layer on OAuth 2.0</li><li>Token binding and proof-of-possession</li><li>Attack vectors and mitigations (code interception, CSRF, etc.)</li><li>Production deployment considerations</li><li>Monitoring and logging OAuth flows</li></ul>
|
|
<h3>Executable Scripts</h3>
|
|
<p><strong>Location</strong>: <code>skills/security/oauth2-implementation/resources/scripts/</code></p>
|
|
<ol><li><strong>validate_oauth_config.py</strong> - OAuth 2.0 server configuration validator</li></ol>
|
|
<ul><li>Validates authorization server configuration files</li><li>Checks grant type security settings</li><li>Validates redirect URI patterns and security</li><li>Detects missing PKCE enforcement</li><li>Audits token lifetime configurations</li><li>Validates CORS settings for token endpoints</li><li>Checks client secret strength</li><li>Provides security recommendations</li><li>Supports JSON output for CI/CD</li><li>Usage: <code>./validate_oauth_config.py --config-file oauth-server.conf --json</code></li></ul>
|
|
<ol><li><strong>test_oauth_flow.py</strong> - OAuth 2.0 flow end-to-end testing</li></ol>
|
|
<ul><li>Tests authorization code flow with PKCE</li><li>Tests client credentials flow</li><li>Tests refresh token rotation</li><li>Validates token response format and claims</li><li>Tests token revocation endpoints</li><li>Validates state parameter handling</li><li>Checks PKCE challenge verification</li><li>Generates detailed test reports</li><li>Supports multiple authorization servers</li><li>Usage: <code>./test_oauth_flow.py --authorization-server https://auth.example.com --flow authorization_code --json</code></li></ul>
|
|
<ol><li><strong>generate_pkce.py</strong> - PKCE challenge and verifier generator</li></ol>
|
|
<ul><li>Generates cryptographically secure code_verifier</li><li>Creates code_challenge using S256 or plain method</li><li>Validates PKCE pairs for testing</li><li>Shows complete OAuth flow with PKCE</li><li>Supports custom verifier lengths (43-128 chars)</li><li>Includes verification function</li><li>Provides usage examples</li><li>Usage: <code>./generate_pkce.py --method S256 --verifier-length 64 --json</code></li></ul>
|
|
<h3>Production-Ready Examples</h3>
|
|
<p><strong>Location</strong>: <code>skills/security/oauth2-implementation/resources/examples/</code></p>
|
|
<ol><li><strong>python/authorization_code_flow.py</strong> - Complete auth code flow with PKCE</li></ol>
|
|
<ul><li>Flask-based client implementation</li><li>PKCE generation and validation</li><li>State parameter CSRF protection</li><li>Automatic token refresh</li><li>Secure token storage patterns</li><li>Error handling and retry logic</li></ul>
|
|
<ol><li><strong>python/client_credentials.py</strong> - Service-to-service authentication</li></ol>
|
|
<ul><li>Client credentials flow implementation</li><li>Token caching with expiration</li><li>Automatic token refresh</li><li>Rate limiting and backoff</li><li>Connection pooling</li></ul>
|
|
<ol><li><strong>python/resource_server.py</strong> - Protected API with token validation</li></ol>
|
|
<ul><li>JWT validation with RS256</li><li>Token introspection support</li><li>Scope-based authorization</li><li>Rate limiting per client</li><li>Comprehensive error responses</li></ul>
|
|
<ol><li><strong>nodejs/oauth-server.js</strong> - OAuth server with node-oauth2-server</li></ol>
|
|
<ul><li>Complete authorization server</li><li>All grant types supported</li><li>PKCE validation</li><li>Refresh token rotation</li><li>PostgreSQL token storage</li></ul>
|
|
<ol><li><strong>python/refresh_token_rotation.py</strong> - Secure refresh token handling</li></ol>
|
|
<ul><li>Refresh token rotation pattern</li><li>Token family tracking (theft detection)</li><li>Automatic revocation on compromise</li><li>Database schema included</li></ul>
|
|
<ol><li><strong>config/keycloak-realm.json</strong> - Keycloak realm configuration</li></ol>
|
|
<ul><li>Production-ready realm setup</li><li>Client configurations for web, mobile, SPA</li><li>Scope definitions</li><li>Token lifetimes</li><li>PKCE enforcement</li></ul>
|
|
<ol><li><strong>typescript/react-oauth-client.tsx</strong> - React OAuth integration</li></ol>
|
|
<ul><li>React hooks for OAuth flow</li><li>PKCE implementation</li><li>Token storage in memory</li><li>Automatic token refresh</li><li>Protected route components</li></ul>
|
|
<ol><li><strong>docker/docker-compose.yml</strong> - Complete OAuth environment</li></ol>
|
|
<ul><li>Authorization server (Keycloak)</li><li>Resource server (API)</li><li>Client application</li><li>PostgreSQL database</li><li>Nginx reverse proxy</li></ul>
|
|
<p>All examples are production-ready, fully commented, and include error handling.</p>
|
|
<hr>
|
|
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/security-oauth2-implementation.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |