API Authentication Patterns: Sessions, Tokens, and Service Credentials
Compare session cookies, bearer tokens, OAuth, and API keys, with practical protections against token leakage and authorization mistakes.
TechSilo
Technology writer & developer
API authentication answers who is making a request. Authorization answers what that identity may do. A secure design needs both—and the right approach depends on whether the caller is a browser user, mobile application, or backend service.
Choose the pattern by caller
| Caller | Common approach | Important consideration |
| --- | --- | --- |
| Browser application | Server-side session with cookie | CSRF protection and cookie settings |
| Mobile or native client | Short-lived access token | Secure token storage and refresh |
| Backend-to-backend | OAuth client credentials or scoped API key | Secret rotation and least privilege |
| Third-party delegated app | OAuth authorization code + PKCE | User consent and audience/scope validation |
These are patterns, not universal prescriptions. The identity provider, threat model, and operational constraints decide the details.
Pattern 1: Server-side session
After verifying login credentials, the server creates an unpredictable session identifier and stores session state server-side. The browser receives a cookie such as:
Set-Cookie: session=opaque-random-id; HttpOnly; Secure; SameSite=Lax; Path=/HttpOnly limits JavaScript access to the cookie, and Secure requires HTTPS. SameSite offers some CSRF protection but may not be sufficient for sensitive state-changing actions. Revoke sessions on logout and regenerate identifiers after authentication transitions.
Pattern 2: Bearer tokens
A bearer token grants access to whoever possesses it. A request might include:
Authorization: Bearer YOUR_SHORT_LIVED_ACCESS_TOKENNever put a production token in source code, public URLs, browser analytics, or client-exposed environment variables. For JWTs, validate the signature, accepted algorithm, issuer, audience, and expiration. Do not assume that merely decoding a JWT verifies its authenticity.
Access tokens should be short-lived. Refresh tokens need stronger storage and rotation/revocation rules.
Pattern 3: Scoped API keys
An API key can be appropriate for server-to-server integration:
const response = await fetch('https://api.example.com/v1/jobs', {
headers: {
Authorization: 'Bearer ' + process.env.SERVICE_API_TOKEN,
},
});
if (!response.ok) throw new Error('Upstream request failed');Run this on a trusted server, not in bundled frontend code. Grant only required permissions, apply per-key limits, record use, and support rotation without downtime.
Prevent the authentication/authorization mix-up
A valid token does not mean the user may read every record:
app.get('/api/projects/:id', requireSession, async (req, res) => {
const project = await findProject(req.params.id);
if (!project) return res.sendStatus(404);
if (project.ownerId !== req.user.id) return res.sendStatus(403);
return res.json(project);
});The functions above are placeholders for your application's database and session implementation. The key point is the per-resource ownership check.
Common mistakes
- Using an API key in NEXT_PUBLIC_* variables where it becomes public.
- Trusting a client-supplied user ID instead of the authenticated identity.
- Putting long-lived bearer tokens in URLs or verbose logs.
- Treating CORS as an access-control mechanism.
- Neglecting rate limits, account recovery, MFA for sensitive operations, and session revocation.
A practical audit
Inventory all authentication methods, identify where secrets are stored, review the scope and lifetime of every credential, and confirm that each private route enforces authorization independently. Also read TechSilo's [CSRF Token Implementation Guide](/blog/practical-csrf-token-implementation-guide-mqw7ifat).
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Environment Variable Management: Secure Secrets and Deployment Practices
Keep environment configuration safe across local development, CI, and production without leaking API keys into browser bundles or logs.
Read postPractical CORS Configuration Security Guide for APIs
Secure cross-origin browser requests with explicit origin allowlists, correct preflight handling, and credential rules.
Read postPractical XSS Protection in React: Escaping, Sanitization, and CSP
Prevent cross-site scripting in React by understanding text escaping, dangerous HTML injection, safe URL handling, and Content Security Policy.
Read postPreventing SQL Injection: Parameterized Queries and Safe Database Access
Learn how SQL injection works and how to prevent it using parameterized queries, least-privilege database accounts, and input validation.
Read postTroubleshooting CORS Errors in Production: Step-by-Step Guide
Diagnose missing CORS headers, blocked OPTIONS preflights, proxy errors, and credential mismatches without weakening API security.
Read post