Blog | G5 Cyber Security

Cross-Subdomain Cookie Authentication

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

  1. Understand Cookie Domains
  • Set the Cookie on Login
  • 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:

  • Access the Cookie on Other Subdomains
  • 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');
      }
    });
    
  • Security Considerations
  • Exit mobile version