Back to articles
API Authentication Done Right: JWTs, API Keys, and OAuth2 in Production

API Authentication Done Right: JWTs, API Keys, and OAuth2 in Production

via Dev.to WebdevYoung Gao

Every backend faces the same question: how do we authenticate requests? Auth Model Comparison Feature API Keys JWTs OAuth2 Best for Server-to-server User sessions, SPAs Delegated access Stateless? No Yes Depends Revocable? Instantly Not until expiry Yes Complexity Low Medium High 1. API Key Authentication Two rules: never store keys in plaintext , always use a prefix . function generateApiKey () { const prefix = " pk_live " ; const secret = crypto . randomBytes ( 32 ). toString ( " base64url " ); const fullKey = ` ${ prefix } _ ${ secret } ` ; const hash = crypto . createHash ( " sha256 " ). update ( fullKey ). digest ( " hex " ); return { key : fullKey , record : { id : crypto . randomUUID (), prefix , hash , createdAt : new Date (), lastUsedAt : null } }; } async function apiKeyAuth ( req : Request , res : Response , next : NextFunction ) { const header = req . headers [ " x-api-key " ]; if ( ! header ) return res . status ( 401 ). json ({ error : " Missing API key " }); const hash =

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
7 views

Related Articles