How to Use OAuth2 for Microservices: Simple Guide
Use
OAuth2 by centralizing authentication in an authorization server that issues tokens. Microservices validate these tokens to allow or deny access, enabling secure and scalable communication.Syntax
The basic OAuth2 flow for microservices involves these parts:
- Authorization Server: Issues access tokens after user login.
- Resource Server (Microservice): Validates tokens to protect APIs.
- Client: Requests tokens and calls microservices with tokens.
Tokens are usually JWT (JSON Web Tokens) containing user info and expiry.
http
POST /oauth/token HTTP/1.1 Host: auth-server.com Content-Type: application/x-www-form-urlencoded grant_type=password&username=user&password=pass&client_id=client123&client_secret=secret Authorization: Bearer <access_token> GET /api/resource HTTP/1.1 Host: microservice.com Authorization: Bearer <access_token>
Example
This example shows a simple Node.js microservice validating an OAuth2 JWT token using the express framework and jsonwebtoken library.
javascript
import express from 'express'; import jwt from 'jsonwebtoken'; const app = express(); const PORT = 3000; const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----\nYOUR_PUBLIC_KEY_HERE\n-----END PUBLIC KEY-----`; // Middleware to check token function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) return res.sendStatus(401); jwt.verify(token, PUBLIC_KEY, { algorithms: ['RS256'] }, (err, user) => { if (err) return res.sendStatus(403); req.user = user; next(); }); } app.get('/api/data', authenticateToken, (req, res) => { res.json({ message: 'Secure data for ' + req.user.name }); }); app.listen(PORT, () => { console.log(`Microservice running on port ${PORT}`); });
Output
Microservice running on port 3000
Common Pitfalls
- Not validating tokens properly: Always verify signature and expiry to avoid security holes.
- Sharing secrets insecurely: Use public/private keys (asymmetric) instead of shared secrets when possible.
- Ignoring token scopes: Check token scopes to restrict access to specific microservice APIs.
- Overloading microservices with auth logic: Keep authentication centralized and microservices focused on token validation.
javascript
/* Wrong: Skipping token verification */ app.get('/api/data', (req, res) => { // No token check here res.json({ message: 'Data without auth' }); }); /* Right: Using middleware to verify token */ app.get('/api/data', authenticateToken, (req, res) => { res.json({ message: 'Data with auth for ' + req.user.name }); });
Quick Reference
- Use an Authorization Server to issue tokens.
- Microservices act as Resource Servers validating tokens.
- Use
JWTtokens with public/private keys for security. - Check token expiry and scopes in microservices.
- Keep authentication logic centralized, microservices only validate tokens.
Key Takeaways
Centralize authentication with an OAuth2 authorization server issuing tokens.
Microservices validate tokens to secure API access without managing user credentials.
Use JWT tokens with proper signature and expiry validation for security.
Check token scopes to enforce fine-grained access control in microservices.
Avoid embedding full auth logic in microservices; keep it focused on token validation.