高级 API 用法

mTLS 身份验证

Mutual TLS(mTLS)可以限制 API 访问,只有出示有效 Client Certificate 的机器才能代表团队发起请求。它非常适合 API 流量经过自有 Gateway、且需要通过密码学证明每个请求都来自授权系统的企业环境。

为什么使用 mTLS?

  • Zero-trust Security — 每个请求都必须使用 Certificate 证明身份,而不只是提供 API Key

  • 适用于 Gateway — 流量通过企业 API Gateway、Proxy 或 Service Mesh 路由时可自然工作

  • 无需修改代码 — 启用后,只需在请求中附加 Client Certificate。所有现有 API 功能(模型、Tool、Streaming)均保持不变

快速开始

1. 完成设置

联系 support@x.ai,并提供:

  • Team ID(可在 xAI Console 中找到)

  • PEM 格式的 CA Certificate

  • 系统将使用的 Client Certificate 中的 Common Name(CN)

我们会配置你的团队,并在 mTLS 激活后进行确认。

2. 指向 mTLS Endpoint

使用 https://mtls.api.x.ai,而不是 https://api.x.ai。这是唯一需要的更改。所有 API Path(/v1/chat/completions/v1/responses/v1/embeddings 等)都以相同方式工作。

3. 附加 Client Certificate

每个请求都要包含 Client Certificate 和 Private Key。示例如下:

curl https://mtls.api.x.ai/v1/chat/completions \\
  --cert /path/to/client-cert.pem \\
  --key /path/to/client-key.pem \\
  -H "Content-Type: application/json" \\
  -H "Authorization: Bearer $XAI_API_KEY" \\
  -d '{
    "messages": [
      {
        "role": "user",
        "content": "Hello, world!"
      }
    ],
    "model": "grok-4.5",
    "stream": false
  }'

身份验证工作原理

为团队启用 mTLS 后,每个请求都要经过两项检查:

  1. Certificate 验证 — Client Certificate 会根据设置时提供的 CA Certificate 进行验证。没有有效 Certificate 的请求会以 403 Forbidden 拒绝。

  2. API Key 验证 — API Key 会照常检查。无效或缺失的 Key 会以 401 Unauthorized 拒绝。

只有两项检查均通过,请求才能继续。其他行为(rate limit、计费、模型访问)与标准 endpoint 完全相同。

轮换 Certificate

mTLS 支持在不中断服务的情况下轮换 Certificate:

场景操作
续期 Client Certificate(相同 CA、相同 CN)无需额外操作,直接开始使用新 Certificate。
更新 CA(例如新的 Intermediate)联系 support@x.ai上传更新后的 CA Bundle。
完全切换到其他 CA联系 support@x.ai注册新的 CA Certificate。

FAQ

必须使用 mTLS Endpoint 吗?

如果团队将 mTLS 启用为必需,则必须使用。发送到 api.x.ai 的请求会因未出示 Client Certificate 而被拒绝。如果部分 API Key 需要在没有 mTLS 的情况下工作,请联系 Support 讨论配置。

mTLS 可以使用 Regional Endpoint 吗?

mTLS 目前可用于全球 mtls.api.x.ai endpoint。如果需要在 Regional Endpoint 中使用 mTLS,请联系 support@x.ai 拒绝。

需要哪种 Certificate 格式?

需要 PEM 格式的 X.509 Certificate。CA Certificate(设置时提供)和 Client Certificate 都必须采用 PEM 编码。

mTLS 按 API Key 还是按团队配置?

mTLS 在团队级别配置。团队中的所有 API Key 共享相同的 mTLS 配置。

如何测试设置?

设置完成后,使用 Certificate 发起一个简单请求:

Bash

curl -v https://mtls.api.x.ai/v1/api-key \\
  --cert /path/to/client-cert.pem \\
  --key /path/to/client-key.pem \\
  -H "Authorization: Bearer $XAI_API_KEY"

响应成功即表示 Certificate 和 API Key 均正常工作。如果看到 403 Forbidden,请检查 Certificate 是否由提供给 xAI 的 CA 签名。