Skip to content

Auth Middleware

Auth middleware allows you to implement custom authentication and authorization logic that runs before other rules in your page rules chain. This enables you to protect routes, implement OAuth flows, or add any custom authentication logic to your site.

Getting Started

To create auth middleware:

  1. Navigate to the “Compute > Auth Middleware” section in the QuantCDN dashboard
  2. Create a new middleware function using the code editor
  3. Apply the middleware to specific routes using Page Rules

How It Works

Auth middleware functions run before other rules in your page rules chain. They must return a response with:

  • Status code 201 to indicate successful authentication and continue to the next rule
  • Any other status code to halt the request (typically 401 for unauthorized or 302 for redirects)

Examples

Basic Authentication

This example implements simple username/password authentication using HTTP Basic Auth:

// This simple example implements basic authentication.
const BASIC_AUTH = "user:pass"
let authHeader = event.request.headers.get('authorization')
if (authHeader != 'Basic ' + btoa(BASIC_AUTH)) {
let headers = new Headers({ "Content-Type": "text/html; charset=utf-8" })
headers.set("WWW-Authenticate", "Basic realm=Authorization Required")
return new Response("Authentication required", {
status: 401,
headers: headers,
});
}
// Return a 201 response when access through the middleware is granted.
return new Response('Authenticated', { status: 201 });

JWT Authentication

This example validates a JWT token from a cookie:

const JWT_SECRET = 'your-secret-key';
async function validateAuth(event) {
const req = event.request;
// Get JWT token from cookie
const token = req.headers.get('Cookie')?.match(/auth_token=([^;]+)/)?.[1];
if (!token) {
return new Response('Unauthorized', { status: 401 });
}
try {
// Verify the JWT token
const secretKey = new TextEncoder().encode(JWT_SECRET);
const { payload } = await jose.jwtVerify(token, secretKey);
// Token is valid, continue to next rule
return new Response('Authenticated', { status: 201 });
} catch (error) {
// Invalid token
return new Response('Unauthorized', { status: 401 });
}
}
return validateAuth(event);

OAuth Integration

Auth middleware can implement OAuth flows with providers like Google, Apple, or GitHub. Here’s a simplified OAuth flow structure:

async function handleOAuth(event) {
const req = event.request;
const url = new URL(event.url);
// Handle OAuth callback
if (url.pathname === '/auth/callback') {
// Verify OAuth code/tokens
// Exchange for access token
// Create session/JWT
// Redirect with cookies set
return new Response('', {
status: 302,
headers: {
'Location': '/',
'Set-Cookie': `auth_token=${token}; HttpOnly; Secure;`,
}
});
}
// Check for existing session
const token = req.headers.get('Cookie')?.match(/auth_token=([^;]+)/)?.[1];
if (token) {
// Validate token
return new Response('Authenticated', { status: 201 });
}
// Show login page or redirect to OAuth provider
return new Response('Login page HTML...', {
status: 200,
headers: { 'Content-Type': 'text/html' }
});
}

Prebuilt Examples

When creating a new auth middleware function, you can select from several prebuilt examples in the code editor. These examples provide ready-to-use authentication implementations for popular platforms:

  • Apple Sign In - Complete implementation of Apple’s OAuth2 flow including JWT validation
  • Google Sign In - OAuth2 implementation for Google authentication
  • X (Twitter) - OAuth 1.0a implementation for X/Twitter authentication
  • Auth0 - Integration with Auth0’s Universal Login
  • Basic Auth - Simple username/password authentication
  • JWT Validation - Token-based authentication using JWTs

To use a prebuilt example:

  1. Click “New Auth Middleware” in the Compute section
  2. Select an example from the dropdown menu in the code editor
  3. Replace the placeholder values (client IDs, secrets, etc.) with your own credentials
  4. Save and apply the middleware using Page Rules

Applying Auth Middleware

To apply auth middleware to routes:

  1. Create a new Page Rule
  2. Configure the matching criteria (domains, paths, etc.)
  3. Select “Authentication” as the action
  4. Choose your auth middleware function

Multiple auth middleware functions can be created and applied to different routes as needed.

Chaining Auth Middleware

Multiple auth middleware functions can be chained together to create sophisticated authentication flows. Each middleware in the chain must return a 201 status code for the next middleware to execute.

Common use cases for chaining include:

  • Multi-factor authentication (MFA/2FA)
  • Email verification
  • Additional security checks
  • Role-based access control

Example: Multi-Step Authentication Flow

Here’s an example of how you might structure a secure authentication chain:

  1. Primary Authentication

    • Validates the user’s initial login credentials
    • Checks if the user has a valid session token
    • Sets necessary session cookies
  2. Email Verification Layer

    • Checks if the user’s email is verified
    • Redirects unverified users to a verification page
    • Allows verified users to proceed
  3. Two-Factor Authentication

    • Checks if 2FA is required for the user
    • Prompts for and validates 2FA codes
    • Maintains 2FA session state

Implementing the Chain

To implement a chain of auth middleware:

  1. Create each middleware function separately in the Compute > Auth Middleware section
  2. Create multiple Page Rules with the same matching criteria
  3. Order the rules so they execute in sequence:
    • Rule 1: Primary Authentication
    • Rule 2: Email Verification Check
    • Rule 3: Two-Factor Authentication
    • Rule 4: Protected Content/Proxy/etc.