
API Authentication: JWT, API Keys, and OAuth2 Compared
API Authentication: JWT, API Keys, and OAuth2 Compared Every API needs authentication. But JWT, API keys, and OAuth2 solve different problems. Here is when to use each. API Keys Simplest approach. Good for server-to-server communication. function apiKeyAuth ( req : Request , res : Response , next : NextFunction ) { const key = req . headers [ " x-api-key " ] as string ; if ( \ ! key ) return res . status ( 401 ). json ({ error : " API key required " }); const client = await db . apiKey . findOne ({ key : hashKey ( key ) }); if ( \ ! client ) return res . status ( 401 ). json ({ error : " Invalid key " }); req . client = client ; next (); } JWT Auth function jwtAuth ( req , res , next ) { const token = req . headers . authorization ?. replace ( " Bearer " , "" ); try { req . user = jwt . verify ( token , process . env . JWT_SECRET ); next (); } catch { res . status ( 401 ). json ({ error : " Invalid " }); } } API Key: server-to-server JWT: user auth, SPAs OAuth2: third-party access Prod
Continue reading on Dev.to Webdev
Opens in a new tab


