TL;DR
This guide shows how to securely authenticate a user across different subdomains (e.g., app.example.com and api.example.com) using cookies. The key is setting the cookie’s domain attribute correctly so all subdomains can access it.
Steps
- Understand Cookie Domains
- By default, cookies are scoped to the subdomain they were set on.
app.example.comsets a cookie only accessible byapp.example.com. - To share a cookie across subdomains, you need to set the
domainattribute when creating the cookie. For example, settingdomain=example.commakes it available to all subdomains ofexample.com.
When a user successfully logs in on your primary subdomain (e.g., app.example.com), set a cookie with the appropriate domain.
// Example using JavaScript/Node.js with Express and cookies library
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.post('/login', (req, res) => {
// ... authentication logic ...
res.cookie('auth_token', 'your_secure_token', {
domain: '.example.com', // Important: Include the leading dot!
path: '/',
secure: true, // Set to true in production (HTTPS only)
httpOnly: true,
sameSite: 'strict' // Recommended for security
});
res.send('Login successful');
});
Important Notes:
- The leading dot (
.example.com) is crucial. It tells the browser to include all subdomains. - Set
secure: truein production environments to ensure cookies are only sent over HTTPS connections. - Use
httpOnly: trueto prevent client-side JavaScript from accessing the cookie, mitigating XSS attacks. - Consider using
sameSite: 'strict'orsameSite: 'lax'for enhanced security against CSRF attacks.
On other subdomains (e.g., api.example.com), your application can automatically access the cookie if it was set with the correct domain.
// Example using JavaScript/Node.js with Express and cookies library
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/protected', (req, res) => {
const authToken = req.cookies.auth_token;
if (authToken) {
// ... verify the token ...
res.send('Protected resource accessed');
} else {
res.status(401).send('Unauthorized');
}
});
- Token Storage: Never store sensitive information directly in the cookie. Use a secure token that references data on your server.
- HTTPS Only: Always use HTTPS to protect cookies from interception.
- XSS Protection: Implement robust XSS prevention measures (e.g., input validation, output encoding) to prevent attackers from stealing cookies. The
httpOnlyflag helps but isn’t a complete solution. - CSRF Protection: Use CSRF tokens in addition to the
sameSiteattribute for added security. - Cookie Expiration: Set appropriate expiration times for your cookies. Short-lived tokens are generally more secure.
- cyber security best practices: Regularly review and update your cyber security measures.