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.
- License 许可
- MIT
- 最近更新
- 2026-09-24
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- cloudflare-zero-trust-access
- license
- MIT
- metadata
- { "version": "1.0.0", "category": "authentication", "keywords": [ "Cloudflare Access", "Zero Trust", "Cloudflare Zero Trust Access", "Access authentication", "JWT validation", "access jwt", "service tokens", "hono cloudflare access", "hono-cloudflare-access middleware", "workers authentication", "protect worker routes", "admin authentication", "access policy", "identity providers", "azure ad access", "google workspace access", "okta access", "github access", "rbac cloudflare", "geographic restrictions", "multi-tenant access", "cors access", "CORS preflight blocked", "JWT header missing", "access key cache", "team mismatch", "access claims" ], "platform": "cloudflare-workers", "framework": "hono", "time_savings": "2.5 hours", "last_verified": "2025-10-28", "token_savings": "58%", "errors_prevented": 8, "package_versions": { "hono": "4.10.3", "@hono/cloudflare-access": "0.3.1", "@cloudflare/workers-types": "4.20251014.0" }, "production_tested": true }
- description
- Cloudflare Zero Trust Access authentication for Workers. Use for JWT validation, service tokens, CORS, or encountering preflight blocking, cache race conditions, missing JWT headers.
- allowed-tools
- [ "Read", "Write", "Edit", "Bash" ]
02 资源文件 17
- 参考文档references/access-policy-setup.md13.5 KB
- 参考文档references/common-errors.md15.1 KB
- 参考文档references/jwt-payload-structure.md12.8 KB
- 参考文档references/quick-start.md1.8 KB
- 参考文档references/service-tokens-guide.md15.3 KB
- 参考文档references/use-cases.md8.1 KB
- 参考文档references/value-proposition.md1.6 KB
- 脚本scripts/create-service-token.sh8.3 KB
- 脚本scripts/test-access-jwt.sh10.8 KB
- 其他templates/.env.example4.2 KB
- 脚本templates/cors-access.ts8.1 KB
- 脚本templates/hono-basic-setup.ts3.8 KB
- 脚本templates/jwt-validation-manual.ts6.6 KB
- 脚本templates/multi-tenant.ts10.1 KB
- 脚本templates/service-token-auth.ts7.5 KB
- 脚本templates/types.ts8.5 KB
- 其他templates/wrangler.jsonc3.9 KB
03 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:
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):
{
"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!
// ✅ 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
// ✅ 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
// ✅ 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 |
.env.example |
Environment variable template |
types.ts |
TypeScript definitions |
Scripts
| Script | Usage |
|---|---|
test-access-jwt.sh |
./test-access-jwt.sh <jwt-token> - Decode and validate JWT |
create-service-token.sh |
./create-service-token.sh [name] - Service token setup guide |
Use Cases
| Use Case | Template | Key Point |
|---|---|---|
| Admin Dashboard | hono-basic-setup.ts |
Email domain policy |
| API Authentication | hono-basic-setup.ts |
Mixed user/service policy |
| SPA + API | cors-access.ts |
CORS before Access! |
| CI/CD Pipeline | service-token-auth.ts |
Service token in secrets |
| Multi-Tenant SaaS | multi-tenant.ts |
D1 tenant config |
📄 Detailed use cases: references/use-cases.md
When to Load References
| Reference File | Load When... |
|---|---|
references/quick-start.md |
Step-by-step setup for new users, first-time integration |
references/common-errors.md |
Debugging auth issues, prevention patterns (includes all 8 errors) |
references/jwt-payload-structure.md |
Accessing JWT claims, user vs service token |
references/service-tokens-guide.md |
Setting up machine-to-machine auth |
references/access-policy-setup.md |
Dashboard configuration, policy creation |
references/use-cases.md |
Detailed implementation for specific scenarios |
references/value-proposition.md |
Token efficiency metrics, workflow guidance, production validation |
Package Versions
| Package | Version |
|---|---|
| @hono/cloudflare-access | 0.3.1 |
| hono | 4.10.7 |
| @cloudflare/workers-types | 4.20251126.0 |
Verified: 2025-12-14 | Token Savings: ~58% | Production Tested: ✅
When NOT to Use
This skill is for Cloudflare Workers with Cloudflare Access. Do not use for:
- ❌ Cloudflare Pages (use
@cloudflare/pages-plugin-cloudflare-accessinstead) - ❌ Non-Cloudflare platforms
- ❌ Custom JWT auth (not Access)
- ❌ Auth.js or other auth libraries
- ❌ Self-hosted authentication
For those, use appropriate skills or libraries.
Additional Resources
Cloudflare Documentation:
Packages:
Dashboard:
Skill Version: 1.0.0 Last Updated: 2025-10-28 Errors Prevented: 8 Token Savings: 58% Time Savings: 2.5 hours Production Tested: ✅
04 同仓库更多 Skills
{TODO=lowercase-hyphen-case-name}
[TODO: Write comprehensive description in third-person. Start with "This skill provides..." or "This skill should be used when..."] [TODO: Add "Use when" scenarios - specific situations where Claude should use this skill] [TODO: Add keywords - technologies, use cases, error messages that should trigger this skill]
zustand-state-management
Zustand state management for React with TypeScript. Use for global state, Redux/Context API migration, localStorage persistence, slices pattern, devtools, Next.js SSR, or encountering hydration errors, TypeScript inference issues, persist middleware problems, infinite render loops.
zod
TypeScript-first schema validation and type inference. Use for validating API requests/responses, form data, env vars, configs, defining type-safe schemas with runtime validation, transforming data, generating JSON Schema for OpenAPI/AI, or encountering missing validation errors, type inference issues, validation error handling problems. Zero dependencies (2kb gzipped).
xss-prevention
XSS attack prevention with input sanitization, output encoding, Content Security Policy. Use for user-generated content, rich text editors, web application security, or encountering stored XSS, reflected XSS, DOM manipulation, script injection errors.
wordpress-plugin-core
WordPress plugin development with hooks, security, REST API, custom post types. Use for plugin creation, $wpdb queries, Settings API, or encountering SQL injection, XSS, CSRF, nonce errors.
woocommerce-dev-cycle
Run tests, linting, and quality checks for WooCommerce development. Use when running tests, fixing code style, or following the development workflow in WooCommerce projects.