Authentication
Using an Authenticated Gateway in AI Gateway adds security by requiring a valid authorization token for each request. This feature is especially useful when storing logs, as it prevents unauthorized access and protects against invalid requests that can inflate log storage usage and make it harder to find the data you need. With Authenticated Gateway enabled, only requests with the correct token are processed.
Setting up Authenticated Gateway using the Dashboard
Section titled “Setting up Authenticated Gateway using the Dashboard”- Go to the Settings for the specific gateway you want to enable authentication for.
- Select Create authentication token to generate a custom token with the required
Run
permissions. Be sure to securely save this token, as it will not be displayed again. - Include the
cf-aig-authorization
header with your API token in each request for this gateway. - Return to the settings page and toggle on Authenticated Gateway.
Example requests with OpenAI
Section titled “Example requests with OpenAI”curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openai/chat/completions \ --header 'cf-aig-authorization: Bearer {CF_AIG_TOKEN}' \ --header 'Authorization: Bearer OPENAI_TOKEN' \ --header 'Content-Type: application/json' \ --data '{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "What is Cloudflare?"}]}'
Using the OpenAI SDK:
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, baseURL: "https://gateway.ai.cloudflare.com/v1/account-id/gateway/openai", defaultHeaders: { "cf-aig-authorization": `Bearer {token}`, },});
Example requests with the Vercel AI SDK
Section titled “Example requests with the Vercel AI SDK”import { createOpenAI } from "@ai-sdk/openai";
const openai = createOpenAI({ baseURL: "https://gateway.ai.cloudflare.com/v1/account-id/gateway/openai", headers: { "cf-aig-authorization": `Bearer {token}`, },});
Expected behavior
Section titled “Expected behavior”The following table outlines gateway behavior based on the authentication settings and header status:
Authentication Setting | Header Info | Gateway State | Response |
---|---|---|---|
On | Header present | Authenticated gateway | Request succeeds |
On | No header | Error | Request fails due to missing authorization |
Off | Header present | Unauthenticated gateway | Request succeeds |
Off | No header | Unauthenticated gateway | Request succeeds |
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Products
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark