Skip to content

Authentication Setup

Temp edited this page Nov 3, 2025 · 1 revision

Authentication Setup

Complete guide to configuring Cloudflare Access (Zero Trust) authentication for D1 Database Manager.

Overview

D1 Manager uses Cloudflare Access (part of Cloudflare Zero Trust) for enterprise-grade authentication. This provides:

  • πŸ” Enterprise SSO - GitHub, Google, Azure AD, Okta, and more
  • πŸ›‘οΈ Zero Trust Security - Network-level protection
  • πŸ”‘ Centralized Management - One place to manage all users
  • πŸ“Š Audit Logs - Track all authentication events
  • πŸ†“ Free Tier - Up to 50 users at no cost

Prerequisites

  • Cloudflare account
  • Domain managed by Cloudflare (or use workers.dev subdomain)
  • D1 Manager deployed to Cloudflare Workers

Authentication Flow

User β†’ Cloudflare Access Login β†’ Identity Provider (GitHub/Google/etc)
     β†’ JWT Token β†’ D1 Manager Worker β†’ Validates JWT β†’ Access Granted

Step-by-Step Setup

Step 1: Access Cloudflare Zero Trust

  1. Go to Cloudflare Zero Trust Dashboard
  2. If prompted, create a new Zero Trust organization
  3. Choose a Team Name (e.g., mycompany)
    • This becomes: https://mycompany.cloudflareaccess.com

Step 2: Configure Identity Provider

Option A: GitHub OAuth (Recommended for Developers)

  1. Navigate to Settings β†’ Authentication
  2. Click Add under Login Methods
  3. Select GitHub
  4. Follow the GitHub OAuth setup:
    • Create a GitHub OAuth App at https://github.com/settings/developers
    • Application name: D1 Manager
    • Homepage URL: https://d1.yourdomain.com
    • Authorization callback URL: https://yourteam.cloudflareaccess.com/cdn-cgi/access/callback
  5. Copy Client ID and Client Secret to Cloudflare
  6. Click Save

Option B: Google OAuth

  1. Navigate to Settings β†’ Authentication
  2. Click Add under Login Methods
  3. Select Google
  4. Follow the Google OAuth setup:
  5. Copy Client ID and Client Secret to Cloudflare
  6. Click Save

Option C: Other Identity Providers

Cloudflare Access supports:

  • Azure AD
  • Okta
  • LinkedIn
  • Facebook
  • Yubico
  • One-time PIN
  • And more...

Follow similar steps for your chosen provider.

Step 3: Create Access Application

  1. Navigate to Access β†’ Applications
  2. Click Add an application
  3. Select Self-hosted
  4. Configure the application:

Application Configuration

Application name:

D1 Database Manager

Session Duration:

24 hours (or your preference)

Application domain:

For custom domain:

Type: Custom
Value: d1.yourdomain.com

For workers.dev subdomain:

Type: Custom
Value: d1-manager.your-account.workers.dev

Application Appearance (Optional)

App Launcher visibility: Visible (shows in Cloudflare Access app launcher)

Logo: Upload a logo (optional)

Custom login page: Use default or create custom

Step 4: Configure Access Policies

Create policies to control who can access D1 Manager.

Policy 1: Allow Specific Users

Policy name: Admin Access

Action: Allow

Configure rules:

  • Rule type: Emails
  • Value: admin@yourdomain.com, developer@yourdomain.com

Policy 2: Allow GitHub Organization

Policy name: GitHub Org Members

Action: Allow

Configure rules:

  • Rule type: GitHub organization
  • Value: your-github-org

Policy 3: Allow Google Domain

Policy name: Company Email Domain

Action: Allow

Configure rules:

  • Rule type: Emails ending in
  • Value: @yourcompany.com

Example Policy Configuration

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Policy: Developer Access            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Action: Allow                       β”‚
β”‚ Session duration: 24 hours          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Include:                            β”‚
β”‚ β€’ Emails ending in @company.com     β”‚
β”‚ β€’ GitHub org: company-dev           β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Exclude:                            β”‚
β”‚ β€’ Country: (none)                   β”‚
β”‚ β€’ IP ranges: (none)                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Step 5: Get Application AUD Tag

After creating the application:

  1. Go to Access β†’ Applications
  2. Click on your D1 Manager application
  3. Scroll to Application Details
  4. Copy the Application Audience (AUD) tag

Example:

a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6

Step 6: Get Team Domain

  1. Go to Settings β†’ General
  2. Copy your Team Domain

Example:

https://mycompany.cloudflareaccess.com

Step 7: Configure Worker Secrets

Set the authentication secrets in your Worker:

# Set Team Domain (include https://)
npx wrangler secret put TEAM_DOMAIN
# Enter: https://yourteam.cloudflareaccess.com

# Set Policy AUD (Application Audience tag)
npx wrangler secret put POLICY_AUD
# Enter: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6

Step 8: Deploy and Test

# Deploy the Worker
npx wrangler deploy

# Visit your application
https://d1.yourdomain.com

You should be redirected to Cloudflare Access login.

Testing Authentication

Test Login Flow

  1. Navigate to your D1 Manager URL
  2. You should see Cloudflare Access login page
  3. Choose your identity provider (GitHub, Google, etc.)
  4. Authenticate with your credentials
  5. You should be redirected back to D1 Manager

Verify JWT Validation

The Worker automatically validates JWTs on every request:

// worker/utils/auth.ts
export async function validateAccessJWT(request: Request, env: Env) {
  // Validates JWT from Cloudflare Access
  // Returns user email if valid
  // Returns null if invalid
}

Check Logs

View authentication logs:

# Worker logs
npx wrangler tail

# Cloudflare Access logs
# Go to: Zero Trust β†’ Logs β†’ Access

Local Development (No Auth)

For local development, authentication is automatically bypassed:

// worker/index.ts
const isLocalhost = isLocalDevelopment(request);

if (isLocalhost) {
  console.log('[Auth] Localhost detected, skipping JWT validation');
  userEmail = 'dev@localhost';
}

This allows testing without setting up authentication.

Advanced Configuration

Multiple Applications

Create separate Access applications for different environments:

  • Production: d1.yourdomain.com
  • Staging: d1-staging.yourdomain.com
  • Development: d1-dev.yourdomain.com

Each can have different policies and AUD tags.

Custom Login Page

  1. Go to Access β†’ Applications β†’ Your Application
  2. Scroll to App Launcher
  3. Enable Custom login page
  4. Enter your custom HTML/CSS

Service Tokens

For API access without browser authentication:

  1. Go to Access β†’ Service Auth β†’ Service Tokens
  2. Click Create Service Token
  3. Name it: D1 Manager API
  4. Copy Client ID and Client Secret
  5. Use in API requests:
curl -H "CF-Access-Client-Id: <client-id>" \
     -H "CF-Access-Client-Secret: <client-secret>" \
     https://d1.yourdomain.com/api/databases

CORS Configuration

If accessing from different domains, update CORS settings in worker/utils/cors.ts:

const allowedOrigins = [
  'https://yourdomain.com',
  'https://app.yourdomain.com',
];

Session Duration

Configure how long users stay logged in:

  1. Go to Access β†’ Applications β†’ Your Application
  2. Edit Session Duration
  3. Options: 15min, 30min, 1hr, 12hr, 24hr, 1 week, 1 month

Security Best Practices

1. Use Least Privilege

Only grant access to users who need it:

βœ… Allow: Developers and DBAs
❌ Deny: Everyone else

2. Enable MFA

Require multi-factor authentication:

  1. Go to Settings β†’ Authentication
  2. Enable Require MFA for your identity provider

3. Monitor Access Logs

Regularly review who's accessing D1 Manager:

  1. Go to Logs β†’ Access
  2. Filter by application name
  3. Review authentication events

4. Set Short Session Duration

For sensitive databases, use shorter sessions:

Production: 1 hour
Staging: 12 hours
Development: 24 hours

5. IP Restrictions (Optional)

Restrict access to specific IP ranges:

  1. Edit your Access Policy
  2. Add Include β†’ IP ranges
  3. Enter your office/VPN IP ranges

6. Country Restrictions (Optional)

Block access from specific countries:

  1. Edit your Access Policy
  2. Add Exclude β†’ Country
  3. Select countries to block

Troubleshooting Authentication

Issue: "Authentication error: 401"

Cause: JWT validation failed

Solutions:

  1. Check TEAM_DOMAIN is correct (include https://)
  2. Verify POLICY_AUD matches your Access application
  3. Clear browser cookies and try again
  4. Check Worker logs: npx wrangler tail

Issue: "Authentication loop"

Cause: JWT cookie not being set or validated

Solutions:

  1. Verify application domain in Access matches your deployed URL
  2. Check browser allows cookies
  3. Try incognito/private browsing mode
  4. Verify no browser extensions blocking cookies

Issue: "Unauthorized access"

Cause: User not in allowed policies

Solutions:

  1. Check Access policies include the user's email or domain
  2. Verify user's GitHub org (if using GitHub OAuth)
  3. Review Access logs to see why user was denied

Issue: "Failed to validate JWT"

Cause: Secrets misconfigured

Solutions:

# Verify secrets are set
npx wrangler secret list

# Re-set secrets
npx wrangler secret put TEAM_DOMAIN
npx wrangler secret put POLICY_AUD

# Redeploy
npx wrangler deploy

Issue: "No authentication prompt"

Cause: Access application not configured for domain

Solutions:

  1. Verify Access application domain matches deployment
  2. Check application is enabled
  3. Verify policies are active

Removing Authentication

To temporarily disable authentication (not recommended for production):

// worker/utils/auth.ts
export async function validateAccessJWT(request: Request, env: Env) {
  // Comment out JWT validation
  // return null;
  
  // Return fake user
  return 'admin@localhost';
}

⚠️ Warning: Only use this for testing. Never deploy without authentication.

Identity Provider Setup Details

GitHub OAuth Detailed Steps

  1. Go to https://github.com/settings/developers
  2. Click OAuth Apps β†’ New OAuth App
  3. Fill in:
    • Application name: D1 Database Manager
    • Homepage URL: https://d1.yourdomain.com
    • Application description: Database management tool
    • Authorization callback URL: https://yourteam.cloudflareaccess.com/cdn-cgi/access/callback
  4. Click Register application
  5. Generate a Client Secret
  6. Copy Client ID and Client Secret to Cloudflare Zero Trust

Google OAuth Detailed Steps

  1. Go to https://console.cloud.google.com/
  2. Create a new project or select existing
  3. Enable Google+ API
  4. Go to Credentials β†’ Create Credentials β†’ OAuth client ID
  5. Configure consent screen if prompted
  6. Choose Web application
  7. Add Authorized redirect URIs:
    • https://yourteam.cloudflareaccess.com/cdn-cgi/access/callback
  8. Copy Client ID and Client Secret to Cloudflare Zero Trust

Next Steps


Need Help? See Troubleshooting or open an issue.

Clone this wiki locally