AgentHarness 课程
Hermes 专题/课程概述

第三课:认证与登录

4种认证方式ChatGPT登录API KeyAccess Token

101 > [ 102 ] > 103 > 104 > 105 > 106 > 107 > 108 > 109 > 110

"认证是第一道门, 选对方式事半功倍" -- Codex 支持 4 种认证方式, 覆盖从个人开发到企业部署的所有场景。

认证概述

OpenAI Codex CLI 在执行任何操作之前, 必须先完成认证。认证决定了:

  • 你以谁的身份调用 API -- 个人账号、团队账号还是服务账号
  • 你有哪些权限 -- 能访问哪些模型、有什么速率限制
  • 费用从哪里扣 -- 个人订阅额度、API 预付费还是企业配额

Codex 提供 4 种认证方式, 按推荐程度排序:

方式命令适用场景推荐度
ChatGPT 登录codex login个人/团队日常开发⭐⭐⭐⭐⭐
API Keycodex login --with-api-keyCI/CD、脚本自动化⭐⭐⭐⭐
Access Tokencodex login --with-access-token高级用户、自定义流程⭐⭐⭐
设备认证codex login --device-auth无浏览器的服务器/SSH⭐⭐

认证信息存储在本地:

~/.codex/
  auth.json        <- 认证凭据 (加密存储)
  config.json      <- 用户配置

安全提示: auth.json 包含敏感凭据, 权限为 600 (仅所有者可读写)。不要手动编辑, 不要提交到版本控制。


方式一:ChatGPT 账号登录(推荐)

这是最简单、最安全的方式, 适合绝大多数用户。它复用你的 ChatGPT 登录会话, 无需管理 API Key。

操作步骤

第一步: 运行登录命令

codex login

终端会显示认证选项:

? How would you like to authenticate?
  > Sign in with ChatGPT
    Use an API key
    Use an access token

第二步: 选择 "Sign in with ChatGPT"

选中后, Codex 会自动打开浏览器, 跳转到 ChatGPT 的授权页面:

https://auth.openai.com/authorize?...

在浏览器中:

  1. 确认你已登录 ChatGPT 账号
  2. 点击 "Authorize" 授权 Codex CLI
  3. 浏览器会显示 "Authorization successful"
  4. 自动跳回终端, 显示 ✅ Successfully authenticated!

第三步: 验证登录状态

codex login status

输出:

Authenticated as: user@example.com
Method: ChatGPT OAuth
Plan: Plus
Models: gpt-4o, gpt-4.1, codex-mini-latest

支持的 ChatGPT 计划

计划支持状态说明
Plus✅ 完全支持个人用户首选, 包含充足的 Codex 额度
Pro✅ 完全支持更高的速率限制和优先访问
Business✅ 完全支持企业级功能, 管理员可集中管控
Edu✅ 完全支持教育机构, 经认证的学校/大学
Enterprise✅ 完全支持大型企业, SSO + 合规审计
Free❌ 不支持需要升级到 Plus 或更高计划

ChatGPT 登录的优势

  1. 无需管理 API Key -- 凭据通过 OAuth 2.0 自动轮换, 不用担心 Key 泄露
  2. 复用现有订阅 -- 如果你已经有 ChatGPT Plus, 不用额外付费
  3. 统一账单 -- Codex 使用量和 ChatGPT 订阅合并计费
  4. SSO 支持 -- 企业版可通过 SAML/OIDC 统一认证

方式二:API Key

API Key 是传统的 OpenAI API 认证方式, 适合自动化场景。

操作步骤

codex login --with-api-key

终端提示输入 Key:

Paste your OpenAI API key, it will be read from stdin:
> sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

粘贴你的 API Key (以 sk- 开头), 按回车确认。

获取 API Key

如果你还没有 API Key:

  1. 访问 platform.openai.com/api-keys
  2. 点击 "Create new secret key"
  3. 给 Key 起一个描述性名称 (如 codex-cli-production)
  4. 复制 Key -- 只显示一次, 丢失后需重新生成
┌─────────────────────────────────────────────┐
│  API Key Created                            │
│                                             │
│  sk-proj-abc123...xyz789                    │
│                                             │
│  ⚠️ Copy this key now. You won't see it    │
│     again.                                  │
│                                             │
│  [Copy] [Done]                              │
└─────────────────────────────────────────────┘

API Key 使用场景

  • CI/CD 流水线: GitHub Actions、GitLab CI 中自动化运行 Codex
  • 脚本集成: 在 shell 脚本或 Python 脚本中调用 Codex
  • 服务器部署: 后台服务长期运行, 不依赖浏览器会话
# GitHub Actions 示例
- name: Run Codex
  env:
    OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
  run: codex run "fix the failing test"

API Key 注意事项

  • API Key 直接关联你的 API 余额, 按 token 计费
  • 建议为不同用途创建不同的 Key, 方便追踪和撤销
  • 设置用量上限, 防止意外超支:
    # 在 OpenAI 后台设置月度预算上限
    # Settings > Limits > Monthly budget: $100
    

方式三:Access Token

Access Token 是一种更灵活的认证方式, 适合需要自定义认证流程的高级用户。

操作步骤

codex login --with-access-token

终端提示输入 Token:

Paste your Codex access token, it will be read from stdin:
> cat-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Access Token 与 API Key 的区别

特性API KeyAccess Token
前缀sk-cat-
来源OpenAI 后台Codex 认证流程
权限范围全 APICodex 专用
刷新机制手动轮换自动刷新
适用场景通用 APICodex CLI 专用

Access Token 使用场景

  • 自定义认证代理: 企业通过内部认证服务器签发 Token
  • 跨设备同步: Token 可以在多台机器间安全迁移
  • 细粒度权限: Token 可以限制只访问 Codex 功能

方式四:设备认证(无浏览器环境)

当你在没有浏览器的环境中工作时 (如 SSH 服务器、Docker 容器、WSL), 设备认证是唯一选择。

操作步骤

codex login --device-auth

终端显示设备码和 URL:

To authenticate, visit: https://auth.openai.com/device
Enter code: ABCD-EFGH

Waiting for authentication...

在任何有浏览器的设备上:

  1. 打开 https://auth.openai.com/device
  2. 输入终端显示的 8 位设备码
  3. 用你的 ChatGPT 账号登录并授权
  4. 终端自动检测到授权完成:
    ✅ Successfully authenticated via device auth!
    

设备认证工作原理

设备认证基于 OAuth 2.0 Device Authorization Grant (RFC 8628):

+-----------+                                +---------------+
|           | (1) POST /device/code           |               |
|  Codex    | ------------------------------> |  Auth Server  |
|  CLI      |                                 |               |
|  (无浏览器)| (2) device_code + user_code     |               |
|           | <------------------------------ |               |
+-----------+                                +-------+-------+
     |                                               |
     | (3) 显示 user_code                             |
     |     等待用户授权                               |
     v                                               |
+-----------+                                +-------+-------+
|  用户在    | (4) 访问 URL + 输入 code       |               |
|  浏览器中  | ------------------------------> |  Auth Server  |
+-----------+                                |               |
                                              | (5) 颁发 Token|
                                              v               |
+-----------+                                +-------+-------+
|  Codex    | (6) 轮询 token endpoint        |               |
|  CLI      | ------------------------------> |  Auth Server  |
|           | <------------------------------ |               |
|           | (7) access_token + refresh_token|               |
+-----------+                                +---------------+

设备认证适用场景

  • 远程服务器: 通过 SSH 连接到 Linux 服务器
  • Docker 容器: CI/CD 中的容器化环境
  • WSL (Windows Subsystem for Linux): WSL 中可能无法直接打开浏览器
  • Cloud IDE: GitHub Codespaces、Gitpod 等在线 IDE
# Docker 示例
FROM ubuntu:22.04
RUN curl -fsSL https://openai.com/install.sh | sh
RUN codex login --device-auth
# 容器内无法打开浏览器, 使用设备认证

查看认证状态

随时查看当前的认证状态:

codex login status

输出示例:

┌─────────────────────────────────────────────┐
│  Codex Authentication Status                │
├─────────────────────────────────────────────┤
│  Authenticated: ✅ Yes                      │
│  Method:        ChatGPT OAuth               │
│  Account:       user@example.com            │
│  Plan:          Plus                        │n│  Token expires: 2026-07-28 10:30:00 UTC     │
│  Models:        gpt-4o, gpt-4.1,            │
│                 codex-mini-latest            │
│  Rate limit:    500 req/min                 │
│  Usage today:   1,234 tokens                │
└─────────────────────────────────────────────┘

检查特定认证方式

# 检查是否通过 API Key 认证
codex login status --verbose

# 输出详细的认证信息, 包括:
# - 认证方式
# - Token 过期时间
# - 权限范围
# - 关联的组织

登出

当你需要切换账号或清理凭据时:

codex logout

输出:

✅ Successfully logged out.
Authentication credentials have been removed.

登出的影响

  • 删除本地存储的 ~/.codex/auth.json 中的凭据
  • 不影响你的 ChatGPT 账号或 API Key 本身
  • 不影响其他设备上的 Codex 登录状态
  • 下次使用 Codex 前需要重新认证

强制重新登录

如果遇到认证异常, 可以强制重新认证:

# 先登出
codex logout

# 再重新登录
codex login

认证最佳实践

1. 优先使用 ChatGPT 登录

对于日常开发, ChatGPT 登录是最安全、最方便的方式:

# 推荐: 日常开发
codex login
# 选择 "Sign in with ChatGPT"

2. CI/CD 使用 API Key + 环境变量

永远不要在代码中硬编码 API Key:

# ❌ 错误做法
codex login --with-api-key <<< "sk-proj-abc123"

# ✅ 正确做法
export OPENAI_API_KEY="$CI_SECRET_KEY"
codex login --with-api-key <<< "$OPENAI_API_KEY"

3. 定期轮换 API Key

# 每 90 天轮换一次 API Key
# 1. 在 OpenAI 后台创建新 Key
# 2. 更新 CI/CD secrets
# 3. 用新 Key 重新登录
# 4. 删除旧 Key

4. 为不同环境使用不同 Key

开发环境: sk-proj-dev-xxx     (低额度, 宽松限制)
测试环境: sk-proj-test-xxx    (中等额度)
生产环境: sk-proj-prod-xxx    (高额度, 严格限制)

5. 保护认证凭据

# 确保 auth.json 权限正确
chmod 600 ~/.codex/auth.json

# 不要提交到版本控制
echo ".codex/auth.json" >> .gitignore

# 不要在日志中打印 Token
codex login --with-api-key <<< "$OPENAI_API_KEY" 2>/dev/null

6. 多人团队的认证管理

个人开发: ChatGPT 登录 (每人用自己的账号)
CI/CD:    共享 API Key (存在 CI secrets 中)
企业:     SSO + 集中管控 (通过 Admin 控制台)

常见认证问题排查

问题 1: "Authentication failed"

❌ Error: Authentication failed
   Please check your credentials and try again.

排查步骤:

  1. 检查网络连接:

    curl -I https://api.openai.com
    # 应该返回 HTTP/2 200
    
  2. 检查 Token 是否过期:

    codex login status
    # 查看 Token expires 时间
    
  3. 重新登录:

    codex logout && codex login
    

问题 2: 浏览器无法打开

❌ Error: Unable to open browser
   Please use --device-auth for headless environments.

解决方案:

# 使用设备认证
codex login --device-auth

# 或手动复制 URL 到浏览器
codex login --no-browser

问题 3: "Invalid API Key"

❌ Error: Invalid API key provided.
   Check your API key at https://platform.openai.com/api-keys

排查步骤:

  1. 确认 Key 格式正确 (以 sk- 开头)
  2. 确认 Key 没有被删除或撤销
  3. 确认 Key 有 Codex 访问权限
  4. 重新生成 Key:
    # 在 OpenAI 后台删除旧 Key, 创建新 Key
    

codex logout codex login --with-api-key <<< "sk-proj-new-key"


### 问题 4: "Rate limit exceeded"

❌ Error: Rate limit exceeded. Please wait before making more requests.


**解决方案:**

1. 等待 60 秒后重试
2. 检查你的计划限额:
   ```bash
   codex login status
   # 查看 Rate limit 行
  1. 升级到更高级别的计划
  2. 减少并发请求数

问题 5: "Token expired"

❌ Error: Token has expired.
   Please run `codex login` to refresh your authentication.

解决方案:

# ChatGPT 登录: 自动刷新, 只需重新登录
codex login

# API Key: Key 本身不会过期, 但可能被撤销
codex login --with-api-key <<< "$OPENAI_API_KEY"

# Access Token: 需要重新获取 Token
codex login --with-access-token <<< "$NEW_TOKEN"

问题 6: 代理/防火墙问题

❌ Error: Connection refused
   Unable to reach authentication server.

排查步骤:

# 检查代理设置
echo $HTTP_PROXY
echo $HTTPS_PROXY

# 如果使用代理, 配置 Codex
codex config set proxy http://proxy.example.com:8080

# 检查防火墙是否允许 HTTPS 出站
nc -zv api.openai.com 443

# 企业环境: 确认白名单包含以下域名:
# - api.openai.com
# - auth.openai.com
# - openai.com

问题 7: 多账号切换

# 查看当前登录的账号
codex login status

# 登出当前账号
codex logout

# 登录另一个账号
codex login
# 选择 "Sign in with ChatGPT"
# 在浏览器中登录不同的 ChatGPT 账号

快速诊断清单

遇到认证问题时, 按顺序检查:

□ 网络是否正常? (curl -I https://api.openai.com)
□ 认证状态? (codex login status)
□ Token 是否过期?
□ API Key 是否有效?
□ 代理/防火墙是否阻断?
□ 是否在正确的目录? (~/.codex/)
□ 文件权限是否正确? (chmod 600 auth.json)

如果以上都正常, 尝试完全重置:

codex logout
rm -rf ~/.codex/auth.json
codex login

小结

认证方式命令最佳场景
ChatGPT 登录codex login日常开发 (推荐)
API Keycodex login --with-api-keyCI/CD 自动化
Access Tokencodex login --with-access-token高级自定义流程
设备认证codex login --device-auth无浏览器环境

下一步: 认证完成后, 你就可以开始使用 Codex 了。下一课我们将学习 Codex 的基本用法和命令。