跳转到内容
搜索文档

已认证的 Gateway

最后更新 查看 MarkdownAgent 设置

AI Gateway 要求每个请求提供有效的 Cloudflare API 令牌。这可以防止未经授权的访问,并防止无效请求导致日志存储使用量膨胀。

使用 REST API 时,在标准 Authorization 标头中传递 Cloudflare API 令牌。使用 gateway.ai.cloudflare.com 上的提供商原生端点时,请改用 cf-aig-authorization 标头。

使用仪表板设置已认证的 Gateway

  1. 前往要启用身份验证的特定 gateway 的设置页面。
  2. 选择 Create authentication token(创建身份验证令牌) 生成具有所需 Run 权限的自定义令牌。请务必安全保存此令牌,因为它不会再次显示。
  3. 在每个请求中包含 API 令牌:
    • 如果使用 REST API(/ai/run),在标准 Authorization 标头中包含 Cloudflare API 令牌。
    • 如果使用 gateway.ai.cloudflare.com 上的提供商原生端点,使用 cf-aig-authorization 标头。
  4. 返回设置页面并开启 Authenticated Gateway。

示例请求

# Run `wrangler whoami` to get your account ID to replace $CLOUDFLARE_ACCOUNT_ID,
# and `wrangler auth token` to get an auth token to replace $CLOUDFLARE_API_TOKEN.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{"model": "openai/gpt-4.1-mini", "messages": [{"role": "user", "content": "What is Cloudflare?"}]}'

使用 OpenAI SDK:

import OpenAI from "openai";

const openai = new OpenAI({
	apiKey: CLOUDFLARE_API_TOKEN,
	baseURL: `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1`,
});

const response = await openai.chat.completions.create({
	model: "openai/gpt-4.1-mini",
	messages: [{ role: "user", content: "What is Cloudflare?" }],
});

使用 Vercel AI SDK:

import { createOpenAI } from "@ai-sdk/openai";

const openai = createOpenAI({
	apiKey: CLOUDFLARE_API_TOKEN,
	baseURL: `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1`,
});

预期行为

下表概述了基于身份验证设置和标头状态的 gateway 行为:

身份验证设置 标头信息 Gateway 状态 响应
开启 有标头 已认证的 gateway 请求成功
开启 无标头 错误 因缺少授权而请求失败
关闭 有标头 未认证的 gateway 请求成功
关闭 无标头 未认证的 gateway 请求成功

这篇文档对您有帮助吗?