Skip to main content
ClaudeWave
Skill213 repo starsupdated 2d ago

cloudflare-zero-trust-access

Cloudflare Zero Trust Access authentication for Workers. Use for JWT validation, service tokens, CORS, or encountering preflight blocking, cache race conditions, missing JWT headers.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/secondsky/claude-skills /tmp/cloudflare-zero-trust-access && cp -r /tmp/cloudflare-zero-trust-access/plugins/cloudflare-zero-trust-access/skills/cloudflare-zero-trust-access ~/.claude/skills/cloudflare-zero-trust-access
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Cloudflare Zero Trust Access Skill

Integrate Cloudflare Zero Trust Access authentication with Cloudflare Workers applications using proven patterns and templates.

---

## Overview

This skill provides complete integration patterns for Cloudflare Access, enabling application-level authentication for Workers without managing your own auth infrastructure.

**What is Cloudflare Access?**
Cloudflare Access is Zero Trust authentication that sits in front of your application, validating users before they reach your Worker. After authentication, Access issues JWT tokens that your Worker validates.

**Key Benefits**:
- No auth infrastructure to maintain
- Integrates with identity providers (Azure AD, Google, Okta, GitHub)
- Service tokens for machine-to-machine auth
- Built-in MFA and session management
- Comprehensive audit logs

---

## When to Use This Skill

Trigger this skill when tasks involve:

- **Authentication**: Protecting Worker routes, securing admin dashboards, API authentication
- **Access Control**: Role-based access (RBAC), group-based permissions, geographic restrictions
- **Service Auth**: Backend services calling Worker APIs, CI/CD pipelines, cron jobs
- **Multi-Tenant**: SaaS apps with organization-level authentication
- **CORS + Auth**: Single-page applications calling protected APIs

**Keywords to Trigger**:
cloudflare access, zero trust, access authentication, JWT validation, service tokens, cloudflare auth, hono access, workers authentication, protect worker routes, admin authentication

---

## Integration Patterns

📖 **New to Cloudflare Access?** Load `references/quick-start.md` for step-by-step setup instructions (15-20 minutes).

### Pattern 1: Hono Middleware (Recommended)

Use `@hono/cloudflare-access` for one-line Access integration.

**When to Use**:
- Building with Hono framework
- Need quick, production-ready setup
- Want automatic JWT validation and key caching

**Template**: `templates/hono-basic-setup.ts`

**Setup**:
```typescript
import { Hono } from 'hono'
import { cloudflareAccess } from '@hono/cloudflare-access'

const app = new Hono<{ Bindings: Env }>()

// Public routes
app.get('/', (c) => c.text('Public page'))

// Protected routes
app.use(
  '/admin/*',
  cloudflareAccess({
    domain: (c) => c.env.ACCESS_TEAM_DOMAIN,
  })
)

app.get('/admin/dashboard', (c) => {
  const { email } = c.get('accessPayload')
  return c.text(`Welcome, ${email}!`)
})
```

**Configuration** (`wrangler.jsonc`):
```jsonc
{
  "vars": {
    "ACCESS_TEAM_DOMAIN": "your-team.cloudflareaccess.com",
    "ACCESS_AUD": "your-app-aud-tag"
  }
}
```

**Benefits**:
- ✅ Automatic JWT validation
- ✅ Public key caching (1-hour TTL)
- ✅ Type-safe with TypeScript
- ✅ Production-tested and maintained

---

### Pattern 2: Manual JWT Validation

**When to Use**: Not using Hono, need custom validation logic

**Template**: `templates/jwt-validation-manual.ts` (~100 lines, uses Web Crypto API)

---

### Pattern 3: Service Token Authentication

**When to Use**: CI/CD pipelines, backend services, cron jobs (no interactive login)

**Client**: Send `CF-Access-Client-Id` + `CF-Access-Client-Secret` headers

**Server**: Same middleware handles both - detect via `!payload.email && payload.common_name`

📄 **Full guide**: `references/service-tokens-guide.md`

---

### Pattern 4: CORS + Access

**When to Use**: SPA (React/Vue/Angular) calling protected API

**⚠️ CRITICAL**: CORS middleware MUST come BEFORE Access middleware!
```typescript
// ✅ CORRECT ORDER
app.use('*', cors({ origin: 'https://app.example.com', credentials: true }))
app.use('/api/*', cloudflareAccess({ domain: (c) => c.env.ACCESS_TEAM_DOMAIN }))
```
**Why**: OPTIONS preflight has no auth headers → Access blocks with 401

📄 **Full pattern**: `templates/cors-access.ts`

---

### Pattern 5: Multi-Tenant

**When to Use**: SaaS with per-org authentication, white-label apps

**Architecture**: Tenant config in D1/KV → Dynamic middleware per request

📄 **Full pattern**: `templates/multi-tenant.ts` and `references/use-cases.md`

---

## Common Errors Prevented

This skill prevents 8 documented errors. Full details: `references/common-errors.md`

### Error #1: CORS Preflight Blocked (45 min saved)

**Problem**: OPTIONS requests return 401, breaking CORS

**Solution**: CORS middleware BEFORE Access middleware
```typescript
// ✅ Correct
app.use('*', cors())
app.use('/api/*', cloudflareAccess({ domain: '...' }))
```

---

### Error #2: Missing JWT Header (30 min saved)

**Problem**: Request not going through Access, no JWT header

**Solution**: Access Worker through Access URL, not direct `*.workers.dev`
```
✅ https://team.cloudflareaccess.com/...
❌ https://worker.workers.dev
```

---

### Error #3: Invalid Team Name (15 min saved)

**Problem**: Hardcoded or wrong team name causes "Invalid issuer"

**Solution**: Use environment variables
```typescript
// ✅ Correct
cloudflareAccess({ domain: (c) => c.env.ACCESS_TEAM_DOMAIN })

// ❌ Wrong
cloudflareAccess({ domain: 'my-team.cloudflareaccess.com' })
```

---

### Errors #4-8 (Quick Reference)

| # | Error | Solution |
|---|-------|----------|
| 4 | Key cache race | Use `@hono/cloudflare-access` (auto-caches) |
| 5 | Wrong service token headers | Use `CF-Access-Client-Id/Secret` (not `Authorization`) |
| 6 | Token expiration (401 after 1 hr) | Handle gracefully, redirect to login |
| 7 | Overlapping policies | Use most specific paths |
| 8 | Dev/prod mismatch | Use environment-specific configs |

📄 **Full error details**: `references/common-errors.md` (~2.5 hours saved per implementation)

---

## Templates

| Template | Purpose |
|----------|---------|
| `hono-basic-setup.ts` | Standard Hono + Access integration |
| `jwt-validation-manual.ts` | Manual JWT verification with Web Crypto |
| `service-token-auth.ts` | Service token patterns |
| `cors-access.ts` | CORS + Access (correct ordering) |
| `multi-tenant.ts` | Multi-tenant architecture |
| `wrangler.jsonc` | Complete Wrangler configuration |
|
access-control-rbacSkill

Role-based access control (RBAC) with permissions and policies. Use for admin dashboards, enterprise access, multi-tenant apps, fine-grained authorization, or encountering permission hierarchies, role inheritance, policy conflicts.

aceternity-uiSkill

100+ animated React components (Aceternity UI) for Next.js with Tailwind. Use for hero sections, parallax, 3D effects, or encountering animation, shadcn CLI integration errors.

ai-elements-chatbotSkill

shadcn/ui AI chat components for conversational interfaces. Use for streaming chat, tool/function displays, reasoning visualization, or encountering Next.js App Router setup, Tailwind v4 integration, AI SDK v5 migration errors.

ai-sdk-coreSkill

Vercel AI SDK v5 for backend AI (text generation, structured output, tools, agents). Multi-provider. Use for server-side AI or encountering AI_APICallError, AI_NoObjectGeneratedError, streaming failures.

ai-sdk-uiSkill

Vercel AI SDK v5 React hooks (useChat, useCompletion, useObject) for AI chat interfaces. Use for React/Next.js AI apps or encountering parse stream errors, no response, streaming issues.

api-authenticationSkill

Secure API authentication with JWT, OAuth 2.0, API keys. Use for authentication systems, third-party integrations, service-to-service communication, or encountering token management, security headers, auth flow errors.

api-changelog-versioningSkill

Creates comprehensive API changelogs documenting breaking changes, deprecations, and migration strategies for API consumers. Use when managing API versions, communicating breaking changes, or creating upgrade guides.

api-contract-testingSkill

Verifies API contracts between services using consumer-driven contracts, schema validation, and tools like Pact. Use when testing microservices communication, preventing breaking changes, or validating OpenAPI specifications.