Files
skills/public/api-api-authentication.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
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]>
2026-09-11 00:27:59 -07:00

778 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>api-api-authentication</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="/api-api-authentication.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/api-api-authentication">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/api-api-authentication.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>api-api-authentication</h1><p class="lede">Implementing API authentication for new services</p><h1>API Authentication</h1>
<p><strong>Scope</strong>: Authentication strategies, JWT, OAuth 2.0, API keys, token management <strong>Lines</strong>: ~784 <strong>Last Updated</strong>: 2025-10-18</p>
<h2>When to Use This Skill</h2>
<p>Activate this skill when:</p>
<ul><li>Implementing API authentication for new services</li><li>Choosing between authentication methods (JWT, OAuth, API keys)</li><li>Securing REST or GraphQL APIs</li><li>Implementing token refresh patterns</li><li>Adding multi-factor authentication (MFA)</li><li>Debugging authentication issues or token validation</li><li>Migrating between authentication strategies</li></ul>
<h2>Core Concepts</h2>
<h3>Authentication vs Authorization</h3>
<p><strong>Authentication</strong>: Verifying identity (&quot;Who are you?&quot;) <strong>Authorization</strong>: Verifying permissions (&quot;What can you do?&quot;)</p>
<p><strong>Example</strong>:</p>
<pre><code>Authentication: User logs in with email/password → Gets token
Authorization: Token includes role &quot;admin&quot; → Can access admin endpoints</code></pre>
<hr>
<h2>Authentication Method Comparison</h2>
<h3>Decision Matrix</h3>
<p>| Method | Best For | Complexity | Mobile-Friendly | Stateless | Revocable | |--------|----------|------------|-----------------|-----------|-----------| | <strong>JWT</strong> | Microservices, mobile apps | Medium | Yes | Yes | No* | | <strong>OAuth 2.0</strong> | Third-party integrations, delegated access | High | Yes | Yes | Yes | | <strong>API Keys</strong> | Server-to-server, simple APIs | Low | Limited | Yes | Yes | | <strong>Sessions</strong> | Traditional web apps | Low | No | No | Yes |</p>
<p>*JWT requires token blacklisting for revocation</p>
<h3>When to Use Each Method</h3>
<p><strong>JWT (JSON Web Tokens)</strong>:</p>
<ul><li>Microservices architecture (no shared session store)</li><li>Mobile apps (persistent authentication)</li><li>Single-page applications (SPAs)</li><li>Stateless APIs</li></ul>
<p><strong>OAuth 2.0</strong>:</p>
<ul><li>Third-party application access (&quot;Sign in with Google&quot;)</li><li>Delegated authorization (access user&#x27;s data without password)</li><li>Multiple clients (web, mobile, desktop)</li><li>Enterprise integrations</li></ul>
<p><strong>API Keys</strong>:</p>
<ul><li>Server-to-server communication</li><li>Internal services</li><li>Simple authentication needs</li><li>Rate limiting by client</li></ul>
<p><strong>Sessions (Cookie-based)</strong>:</p>
<ul><li>Traditional server-rendered web apps</li><li>Need immediate revocation</li><li>Single domain applications</li></ul>
<hr>
<h2>JWT (JSON Web Tokens)</h2>
<h3>Structure</h3>
<p>A JWT consists of three Base64-encoded parts separated by dots:</p>
<pre><code>header.payload.signature</code></pre>
<p><strong>Example</strong>:</p>
<pre><code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</code></pre>
<h3>Header</h3>
<p>Contains token type and signing algorithm:</p>
<pre><code class="lang-json">{
&quot;alg&quot;: &quot;HS256&quot;, // Algorithm (HS256, RS256)
&quot;typ&quot;: &quot;JWT&quot; // Token type
}</code></pre>
<p><strong>Algorithms</strong>:</p>
<ul><li><code>HS256</code> (HMAC SHA-256): Symmetric, shared secret</li><li><code>RS256</code> (RSA SHA-256): Asymmetric, public/private key</li><li><code>ES256</code> (ECDSA SHA-256): Asymmetric, elliptic curve</li></ul>
<h3>Payload (Claims)</h3>
<p>Contains user data and metadata:</p>
<pre><code class="lang-json">{
&quot;sub&quot;: &quot;1234567890&quot;, // Subject (user ID)
&quot;name&quot;: &quot;John Doe&quot;, // Custom claim
&quot;email&quot;: &quot;[email protected]&quot;, // Custom claim
&quot;role&quot;: &quot;admin&quot;, // Custom claim
&quot;iat&quot;: 1516239022, // Issued at (Unix timestamp)
&quot;exp&quot;: 1516242622, // Expiration (Unix timestamp)
&quot;nbf&quot;: 1516239022, // Not before
&quot;iss&quot;: &quot;https://api.example.com&quot;, // Issuer
&quot;aud&quot;: &quot;https://app.example.com&quot; // Audience
}</code></pre>
<p><strong>Standard claims</strong>:</p>
<ul><li><code>sub</code>: Subject (user identifier)</li><li><code>exp</code>: Expiration time (required for security)</li><li><code>iat</code>: Issued at</li><li><code>iss</code>: Issuer (who created the token)</li><li><code>aud</code>: Audience (who the token is for)</li></ul>
<h3>Signature</h3>
<p>Ensures token integrity:</p>
<pre><code class="lang-javascript">// HS256 (symmetric)
HMACSHA256(
base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),
secret_key
)
// RS256 (asymmetric)
RSASHA256(
base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),
private_key
)</code></pre>
<h3>JWT Implementation Examples</h3>
<h4>Python (PyJWT)</h4>
<pre><code class="lang-python">import jwt
from datetime import datetime, timedelta
# Generate token
def create_token(user_id: int, role: str) -&gt; str:
payload = {
&quot;sub&quot;: str(user_id),
&quot;role&quot;: role,
&quot;iat&quot;: datetime.utcnow(),
&quot;exp&quot;: datetime.utcnow() + timedelta(hours=1)
}
return jwt.encode(payload, &quot;your-secret-key&quot;, algorithm=&quot;HS256&quot;)
# Validate token
def validate_token(token: str) -&gt; dict:
try:
payload = jwt.decode(
token,
&quot;your-secret-key&quot;,
algorithms=[&quot;HS256&quot;],
options={&quot;verify_exp&quot;: True}
)
return payload
except jwt.ExpiredSignatureError:
raise Exception(&quot;Token has expired&quot;)
except jwt.InvalidTokenError:
raise Exception(&quot;Invalid token&quot;)</code></pre>
<h4>Node.js (jsonwebtoken)</h4>
<pre><code class="lang-typescript">import jwt from &#x27;jsonwebtoken&#x27;;
// Generate token
function createToken(userId: string, role: string): string {
return jwt.sign(
{ sub: userId, role },
process.env.JWT_SECRET,
{ expiresIn: &#x27;1h&#x27;, algorithm: &#x27;HS256&#x27; }
);
}
// Validate token
function validateToken(token: string): any {
try {
return jwt.verify(token, process.env.JWT_SECRET, {
algorithms: [&#x27;HS256&#x27;]
});
} catch (error) {
if (error.name === &#x27;TokenExpiredError&#x27;) {
throw new Error(&#x27;Token expired&#x27;);
}
throw new Error(&#x27;Invalid token&#x27;);
}
}</code></pre>
<h4>Go (golang-jwt)</h4>
<pre><code class="lang-go">import (
&quot;time&quot;
&quot;github.com/golang-jwt/jwt/v5&quot;
)
type Claims struct {
UserID int `json:&quot;sub&quot;`
Role string `json:&quot;role&quot;`
jwt.RegisteredClaims
}
// Generate token
func CreateToken(userID int, role string) (string, error) {
claims := &amp;Claims{
UserID: userID,
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(&quot;your-secret-key&quot;))
}
// Validate token
func ValidateToken(tokenString string) (*Claims, error) {
claims := &amp;Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(&quot;your-secret-key&quot;), nil
})
if err != nil || !token.Valid {
return nil, err
}
return claims, nil
}</code></pre>
<h3>JWT Best Practices</h3>
<p>✅ <strong>Always set expiration</strong> (<code>exp</code> claim) - Short-lived tokens (15min-1hr) ✅ <strong>Use strong secret keys</strong> - At least 256 bits for HS256 ✅ <strong>Validate signature</strong> - Always verify before trusting payload ✅ <strong>Use RS256 for microservices</strong> - Public key validation, no shared secret ✅ <strong>Store minimal data</strong> - JWTs sent with every request (size matters)</p>
<p>❌ <strong>Don&#x27;t store sensitive data</strong> - JWTs are readable (Base64 encoded, not encrypted) ❌ <strong>Don&#x27;t use for session management alone</strong> - Hard to revoke ❌ <strong>Don&#x27;t store in localStorage</strong> - Vulnerable to XSS attacks ❌ <strong>Don&#x27;t make tokens long-lived</strong> - Compromised tokens can&#x27;t be revoked</p>
<hr>
<h2>OAuth 2.0</h2>
<h3>OAuth 2.0 Flows</h3>
<h4>Authorization Code Flow (Most Secure)</h4>
<p><strong>Use case</strong>: Server-side web apps, mobile apps with PKCE</p>
<pre><code>User Client App Auth Server Resource Server
| | | |
|--1. Click &quot;Login&quot;------&gt;| | |
| |--2. Redirect to-------&gt;| |
| | /authorize | |
|&lt;------3. Login page---------------------------| |
| | | |
|--4. Enter credentials------------------------&gt;| |
| | | |
|&lt;--5. Redirect with authorization code---------| |
| (to callback URL) | | |
| | | |
|--6. Code to client-----&gt;| | |
| |--7. Exchange code-----&gt;| |
| | for tokens | |
| |&lt;--8. Access token------| |
| | + Refresh token | |
| | | |
| |--9. Request with access token-----------------&gt;|
| |&lt;--10. Protected resource-----------------------|</code></pre>
<p><strong>Implementation (Python with Authlib)</strong>:</p>
<pre><code class="lang-python">from authlib.integrations.flask_client import OAuth
oauth = OAuth(app)
oauth.register(
&#x27;google&#x27;,
client_id=&#x27;YOUR_CLIENT_ID&#x27;,
client_secret=&#x27;YOUR_CLIENT_SECRET&#x27;,
server_metadata_url=&#x27;https://accounts.google.com/.well-known/openid-configuration&#x27;,
client_kwargs={&#x27;scope&#x27;: &#x27;openid email profile&#x27;}
)
@app.route(&#x27;/login&#x27;)
def login():
redirect_uri = url_for(&#x27;callback&#x27;, _external=True)
return oauth.google.authorize_redirect(redirect_uri)
@app.route(&#x27;/callback&#x27;)
def callback():
token = oauth.google.authorize_access_token()
user_info = oauth.google.parse_id_token(token)
# Store token and user_info in session
return redirect(&#x27;/dashboard&#x27;)</code></pre>
<h4>Client Credentials Flow (Server-to-Server)</h4>
<p><strong>Use case</strong>: Service-to-service authentication (no user involved)</p>
<pre><code>Service A Auth Server
| |
|--1. POST /token---------&gt;|
| (client_id + secret) |
| |
|&lt;--2. Access token--------|
| |
|--3. API request---------&gt;|
| with access token |</code></pre>
<p><strong>Implementation</strong>:</p>
<pre><code class="lang-python">import requests
# Get access token
response = requests.post(&#x27;https://auth.example.com/oauth/token&#x27;, data={
&#x27;grant_type&#x27;: &#x27;client_credentials&#x27;,
&#x27;client_id&#x27;: &#x27;your_client_id&#x27;,
&#x27;client_secret&#x27;: &#x27;your_client_secret&#x27;,
&#x27;scope&#x27;: &#x27;read write&#x27;
})
token = response.json()[&#x27;access_token&#x27;]
# Use token to access API
api_response = requests.get(
&#x27;https://api.example.com/resource&#x27;,
headers={&#x27;Authorization&#x27;: f&#x27;Bearer {token}&#x27;}
)</code></pre>
<h4>Refresh Token Flow</h4>
<p><strong>Use case</strong>: Get new access token without re-authentication</p>
<pre><code>Client Auth Server
| |
|--1. POST /token----------&gt;|
| (refresh_token) |
| |
|&lt;--2. New access token-----|
| + New refresh token |</code></pre>
<p><strong>Implementation</strong>:</p>
<pre><code class="lang-typescript">async function refreshAccessToken(refreshToken: string): Promise&lt;string&gt; {
const response = await fetch(&#x27;https://auth.example.com/oauth/token&#x27;, {
method: &#x27;POST&#x27;,
headers: { &#x27;Content-Type&#x27;: &#x27;application/json&#x27; },
body: JSON.stringify({
grant_type: &#x27;refresh_token&#x27;,
refresh_token: refreshToken,
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET
})
});
const data = await response.json();
return data.access_token;
}</code></pre>
<h3>OAuth 2.0 Best Practices</h3>
<p>✅ <strong>Use PKCE</strong> (Proof Key for Code Exchange) for mobile/SPAs ✅ <strong>Validate redirect URIs</strong> - Prevent authorization code interception ✅ <strong>Short-lived access tokens</strong> (5-15 minutes) + long-lived refresh tokens ✅ <strong>Store refresh tokens securely</strong> - Encrypted database or secure storage ✅ <strong>Implement token rotation</strong> - Issue new refresh token on each use</p>
<hr>
<h2>API Keys</h2>
<h3>When to Use API Keys</h3>
<p><strong>Best for</strong>:</p>
<ul><li>Server-to-server communication</li><li>Internal microservices</li><li>Third-party integrations (customers accessing your API)</li><li>Rate limiting and usage tracking</li></ul>
<p><strong>Not suitable for</strong>:</p>
<ul><li>User authentication (use JWT or sessions)</li><li>Frontend apps (keys exposed to users)</li></ul>
<h3>API Key Implementation</h3>
<pre><code class="lang-python">import secrets
import hashlib
from datetime import datetime
# Generate API key
def generate_api_key() -&gt; tuple[str, str]:
# Generate random key
key = secrets.token_urlsafe(32) # 32 bytes = 256 bits
# Hash for storage
key_hash = hashlib.sha256(key.encode()).hexdigest()
return key, key_hash # Return both (show key once, store hash)
# Validate API key
def validate_api_key(provided_key: str) -&gt; bool:
provided_hash = hashlib.sha256(provided_key.encode()).hexdigest()
# Look up in database
stored_key = db.query(&quot;SELECT key_hash FROM api_keys WHERE key_hash = ?&quot;, [provided_hash])
return stored_key is not None</code></pre>
<h3>API Key Storage</h3>
<p><strong>Database schema</strong>:</p>
<pre><code class="lang-sql">CREATE TABLE api_keys (
id SERIAL PRIMARY KEY,
key_hash VARCHAR(64) NOT NULL UNIQUE, -- SHA-256 hash
user_id INT NOT NULL,
name VARCHAR(255), -- Key description
scopes TEXT[], -- Permissions
rate_limit_per_hour INT DEFAULT 1000,
created_at TIMESTAMP DEFAULT NOW(),
last_used_at TIMESTAMP,
expires_at TIMESTAMP,
revoked BOOLEAN DEFAULT FALSE
);
CREATE INDEX idx_api_keys_hash ON api_keys(key_hash);
CREATE INDEX idx_api_keys_user ON api_keys(user_id);</code></pre>
<h3>API Key Middleware (FastAPI)</h3>
<pre><code class="lang-python">from fastapi import Security, HTTPException, status
from fastapi.security import APIKeyHeader
import hashlib
api_key_header = APIKeyHeader(name=&quot;X-API-Key&quot;, auto_error=False)
async def validate_api_key(api_key: str = Security(api_key_header)):
if not api_key:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=&quot;API key required&quot;
)
key_hash = hashlib.sha256(api_key.encode()).hexdigest()
# Check database
key_data = await db.fetch_one(
&quot;SELECT * FROM api_keys WHERE key_hash = ? AND revoked = FALSE&quot;,
[key_hash]
)
if not key_data:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=&quot;Invalid API key&quot;
)
# Check expiration
if key_data[&#x27;expires_at&#x27;] and key_data[&#x27;expires_at&#x27;] &lt; datetime.now():
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=&quot;API key expired&quot;
)
# Update last_used_at
await db.execute(
&quot;UPDATE api_keys SET last_used_at = NOW() WHERE id = ?&quot;,
[key_data[&#x27;id&#x27;]]
)
return key_data</code></pre>
<hr>
<h2>Token Storage and Transmission</h2>
<h3>Storage Options</h3>
<p>| Storage | Pros | Cons | Best For | |---------|------|------|----------| | <strong>httpOnly Cookie</strong> | XSS-safe, automatic sending | CSRF risk (needs protection) | Web apps (same domain) | | <strong>localStorage</strong> | Persistent, easy access | XSS vulnerable | Not recommended | | <strong>sessionStorage</strong> | Tab-scoped, cleared on close | XSS vulnerable | Temporary data | | <strong>Memory (React state)</strong> | XSS-safe if no innerHTML | Lost on refresh | SPAs with refresh tokens | | <strong>Secure native storage</strong> | OS-level encryption | Platform-specific | Mobile apps |</p>
<h3>Recommended: httpOnly Cookie (Web Apps)</h3>
<pre><code class="lang-python">from fastapi import Response
@app.post(&#x27;/login&#x27;)
async def login(response: Response, credentials: LoginRequest):
# Validate credentials
user = authenticate(credentials.email, credentials.password)
# Generate token
token = create_jwt(user.id, user.role)
# Set httpOnly cookie
response.set_cookie(
key=&quot;access_token&quot;,
value=token,
httponly=True, # Not accessible via JavaScript (XSS protection)
secure=True, # HTTPS only
samesite=&quot;strict&quot;, # CSRF protection
max_age=3600 # 1 hour
)
return {&quot;message&quot;: &quot;Login successful&quot;}</code></pre>
<h3>Transmission: Authorization Header</h3>
<p><strong>Bearer token</strong> (standard for JWTs and OAuth):</p>
<pre><code class="lang-bash">GET /api/user/profile HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</code></pre>
<p><strong>API key header</strong>:</p>
<pre><code class="lang-bash">GET /api/data HTTP/1.1
Host: api.example.com
X-API-Key: sk_live_abc123def456...</code></pre>
<hr>
<h2>Token Refresh Patterns</h2>
<h3>Pattern 1: Automatic Refresh (Before Expiration)</h3>
<pre><code class="lang-typescript">let accessToken = &#x27;...&#x27;;
let refreshToken = &#x27;...&#x27;;
let tokenExpiry = Date.now() + 3600000; // 1 hour
// Interceptor to refresh token before requests
async function getValidToken(): Promise&lt;string&gt; {
// Refresh 5 minutes before expiry
if (Date.now() &gt; tokenExpiry - 300000) {
const response = await fetch(&#x27;/auth/refresh&#x27;, {
method: &#x27;POST&#x27;,
body: JSON.stringify({ refresh_token: refreshToken })
});
const data = await response.json();
accessToken = data.access_token;
tokenExpiry = Date.now() + data.expires_in * 1000;
if (data.refresh_token) {
refreshToken = data.refresh_token; // Token rotation
}
}
return accessToken;
}</code></pre>
<h3>Pattern 2: Retry on 401 (After Expiration)</h3>
<pre><code class="lang-typescript">async function apiRequest(url: string, options: RequestInit = {}) {
const response = await fetch(url, {
...options,
headers: {
...options.headers,
&#x27;Authorization&#x27;: `Bearer ${accessToken}`
}
});
// Token expired
if (response.status === 401) {
// Refresh token
const newToken = await refreshAccessToken(refreshToken);
accessToken = newToken;
// Retry original request
return fetch(url, {
...options,
headers: {
...options.headers,
&#x27;Authorization&#x27;: `Bearer ${accessToken}`
}
});
}
return response;
}</code></pre>
<hr>
<h2>Multi-Factor Authentication (MFA)</h2>
<h3>TOTP (Time-based One-Time Password)</h3>
<p><strong>Use case</strong>: Second factor for sensitive operations</p>
<pre><code class="lang-python">import pyotp
import qrcode
from io import BytesIO
# Generate MFA secret for user
def setup_mfa(user_id: int) -&gt; dict:
secret = pyotp.random_base32()
# Store secret in database (encrypted)
db.execute(
&quot;UPDATE users SET mfa_secret = ? WHERE id = ?&quot;,
[encrypt(secret), user_id]
)
# Generate QR code for authenticator app
totp_uri = pyotp.totp.TOTP(secret).provisioning_uri(
name=user.email,
issuer_name=&quot;YourApp&quot;
)
qr = qrcode.make(totp_uri)
buffer = BytesIO()
qr.save(buffer, format=&#x27;PNG&#x27;)
return {
&quot;secret&quot;: secret, # Show once to user
&quot;qr_code&quot;: buffer.getvalue()
}
# Verify MFA code
def verify_mfa(user_id: int, code: str) -&gt; bool:
user = db.fetch_one(&quot;SELECT mfa_secret FROM users WHERE id = ?&quot;, [user_id])
secret = decrypt(user[&#x27;mfa_secret&#x27;])
totp = pyotp.TOTP(secret)
return totp.verify(code, valid_window=1) # Allow 30s window</code></pre>
<h3>MFA Login Flow</h3>
<pre><code>1. User enters email/password
2. Validate credentials → Generate temporary token
3. Require MFA code (SMS, TOTP, email)
4. Validate MFA code
5. Issue full access token</code></pre>
<hr>
<h2>Security Checklist</h2>
<h3>JWT Security</h3>
<ul><li>[ ] Set short expiration (<code>exp</code> claim: 15min-1hr)</li><li>[ ] Use strong secret key (256+ bits for HS256)</li><li>[ ] Always validate signature before trusting payload</li><li>[ ] Use RS256 for microservices (public key validation)</li><li>[ ] Don&#x27;t store sensitive data in payload</li><li>[ ] Validate <code>iss</code> (issuer) and <code>aud</code> (audience) claims</li><li>[ ] Implement token blacklist for logout (if needed)</li></ul>
<h3>OAuth 2.0 Security</h3>
<ul><li>[ ] Use PKCE for mobile/SPAs</li><li>[ ] Validate redirect URIs (exact match)</li><li>[ ] Use state parameter (CSRF protection)</li><li>[ ] Short-lived access tokens (5-15min)</li><li>[ ] Secure refresh token storage (encrypted database)</li><li>[ ] Implement refresh token rotation</li><li>[ ] Use HTTPS only for token endpoints</li></ul>
<h3>API Key Security</h3>
<ul><li>[ ] Generate cryptographically secure keys (256+ bits)</li><li>[ ] Store hashed keys only (SHA-256 or better)</li><li>[ ] Implement rate limiting per key</li><li>[ ] Support key revocation</li><li>[ ] Set expiration dates</li><li>[ ] Log key usage for audit trail</li><li>[ ] Use HTTPS only for key transmission</li><li>[ ] Never expose keys in URLs (use headers)</li></ul>
<h3>General Security</h3>
<ul><li>[ ] Use HTTPS everywhere</li><li>[ ] Implement rate limiting</li><li>[ ] Log authentication attempts (detect brute force)</li><li>[ ] Use CORS appropriately</li><li>[ ] Implement CSRF protection for cookies</li><li>[ ] Validate all inputs</li><li>[ ] Use secure password hashing (bcrypt, Argon2)</li><li>[ ] Implement account lockout after failed attempts</li></ul>
<hr>
<h2>Auth Method Decision Tree</h2>
<pre><code>Start: What are you building?
│
├─ Third-party access (users sign in with Google/GitHub)?
│ └─ Use OAuth 2.0 (Authorization Code Flow + PKCE)
│
├─ Server-to-server communication?
│ └─ Use API Keys (with rate limiting)
│
├─ Mobile app or SPA?
│ ├─ Need user identity from third party?
│ │ └─ OAuth 2.0 + JWT
│ └─ Custom authentication?
│ └─ JWT (access + refresh tokens)
│
├─ Microservices architecture?
│ └─ JWT with RS256 (public key validation)
│
├─ Traditional web app (server-rendered)?
│ └─ Sessions (httpOnly cookies) or JWT (cookies)
│
└─ Internal admin tool?
└─ Sessions (simplest) or API Keys</code></pre>
<hr>
<h2>Level 3 Resources</h2>
<p>This skill includes comprehensive reference materials, executable scripts, and implementation examples.</p>
<h3>Reference Materials</h3>
<p><strong><code>api-authentication/resources/REFERENCE.md</code></strong> (~300 lines):</p>
<ul><li>JWT specification (RFC 7519) - Complete technical reference</li><li>OAuth 2.0 framework (RFC 6749) - Authorization flows and grant types</li><li>PKCE extension (RFC 7636) - Proof Key for Code Exchange</li><li>Token storage best practices - Browser, mobile, server-side</li><li>Security considerations - Algorithm confusion, CSRF, XSS, token replay</li><li>Attack vectors and mitigations - Comprehensive security guide</li><li>Password hashing algorithms - Argon2, bcrypt, scrypt comparison</li><li>Implementation checklist - JWT, OAuth, API key requirements</li></ul>
<h3>Executable Scripts</h3>
<p><strong><code>api-authentication/resources/scripts/</code></strong>:</p>
<ol><li><strong>test_jwt.py</strong> - JWT security testing and validation</li></ol>
<ul><li>Validate JWT tokens with full security checks</li><li>Generate tokens with proper claims</li><li>Inspect token structure (header, payload, signature)</li><li>Run attack tests (none algorithm, weak secrets, algorithm confusion)</li><li>Check expiration, signature, and claim validation</li></ul>
<ol><li><strong>test_oauth_flow.py</strong> - OAuth 2.0 flow validator</li></ol>
<ul><li>Test authorization endpoints (Authorization Code Flow)</li><li>Test token endpoints (Client Credentials, Refresh Token)</li><li>Validate PKCE implementation</li><li>Check state parameter and redirect URI validation</li><li>Verify HTTPS enforcement</li></ul>
<ol><li><strong>benchmark_hashing.py</strong> - Password hashing benchmark</li></ol>
<ul><li>Compare bcrypt, Argon2id, and scrypt</li><li>Auto-tune Argon2 parameters for target time (250-500ms)</li><li>Statistical analysis (mean, median, stdev)</li><li>Memory usage comparison</li></ul>
<p><strong>Usage Examples</strong>:</p>
<pre><code class="lang-bash"># JWT validation
python test_jwt.py --token &quot;eyJhbGc...&quot; --validate --secret &quot;key&quot; --algorithm HS256
# OAuth testing
python test_oauth_flow.py --auth-url https://auth.example.com/authorize \
--client-id ID --redirect-uri https://app.example.com/callback
# Hashing benchmark
python benchmark_hashing.py --compare --iterations 50</code></pre>
<h3>Implementation Examples</h3>
<p><strong><code>api-authentication/resources/examples/</code></strong>:</p>
<ul><li><strong>python/jwt_authentication.py</strong> - Complete FastAPI JWT auth with Argon2</li><li><strong>typescript/jwt-auth-client.ts</strong> - React/TypeScript auth client with automatic refresh</li><li><strong>ci-cd/jwt-security-check.yml</strong> - GitHub Actions security validation</li></ul>
<p>See <code>api-authentication/resources/scripts/README.md</code> for detailed documentation.</p>
<hr>
<h2>Related Skills</h2>
<ul><li><code>network-resilience-patterns.md</code> - Retry logic for auth failures</li><li><code>modal-web-endpoints.md</code> - Securing Modal endpoints with auth</li><li><code>ios-networking.md</code> - iOS auth patterns with URLSession</li><li><code>database-selection.md</code> - Storing user credentials and tokens</li></ul>
<hr>
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic) <strong>Resources</strong>: Level 3 (Reference, Scripts, Examples)</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="/api-api-authentication.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>