logo
0
0
Login
Jason Wang<you@example.com>
增加产品手册

CodeBuddy OAuth 2.0 第三方应用的 CodeBuddy 登录示例

CodeBuddy 开放平台是一个为第三方开发者提供的完整生态系统,通过开放 API 和 OAuth 2.0 授权框架,让第三方应用能够安全、高效地集成 CodeBuddy 核心功能。

产品手册

CodeBuddy 开放平台产品手册

📸 应用截图

CodeBuddy OAuth 授权页面

CodeBuddy OAuth 授权页面 - 用户可选择授权方式

🚀 快速开始

1. 安装依赖

npm install

2. 配置环境变量

在项目根目录创建 .env 文件:

# OAuth 配置 CLIENT_ID=你的客户端ID CLIENT_SECRET=你的客户端密钥 REDIRECT_URI=http://localhost:3000/callback # OAuth Endpoints AUTHORIZATION_ENDPOINT=https://copilot.tencent.com/oauth2/authorize TOKEN_ENDPOINT=https://copilot.tencent.com/oauth2/token USERINFO_ENDPOINT=https://copilot.tencent.com/oauth2/userinfo # 应用配置 PORT=3000 SESSION_SECRET=你的会话密钥

3. 启动服务器

npm start

4. 访问应用

打开浏览器访问:http://localhost:3000

📋 功能特性

  • ✅ OAuth 2.0 Authorization Code 流程
  • ✅ OpenID Connect (OIDC) 支持
  • ✅ 使用 form-urlencoded 格式(OAuth 标准)
  • ✅ CSRF 防护(state 参数)
  • ✅ 访问令牌自动刷新
  • ✅ 现代化 UI 设计

🔐 OAuth 流程

1. 用户点击登录 ↓ 2. 重定向到 CodeBuddy 授权页面 https://copilot.tencent.com/oauth2/authorize ↓ 3. 用户授权 ↓ 4. 回调到应用并交换 access_token 使用 application/x-www-form-urlencoded 格式 ↓ 5. 获取用户信息并显示

📝 关键代码说明

授权请求

authUrl.searchParams.append('scope', 'openid'); authUrl.searchParams.append('response_mode', 'query');

令牌交换(使用 form-urlencoded 格式)

const tokenParams = new URLSearchParams({ grant_type: 'authorization_code', client_id: config.clientId, client_secret: config.clientSecret, code: code, redirect_uri: config.redirectUri }); axios.post(url, tokenParams.toString(), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });

🎯 端点配置

端点类型URL
授权端点https://copilot.tencent.com/oauth2/authorize
令牌端点https://copilot.tencent.com/oauth2/token
用户信息端点https://copilot.tencent.com/oauth2/userinfo

🔍 调试

服务器会输出详细日志:

🚀 发起授权: https://copilot.tencent.com/oauth2/authorize?... 🔄 交换授权码... ✅ 令牌交换成功!

📚 文件结构

oauth_test/ ├── server.js # Express 服务器 ├── package.json # 依赖管理 ├── .env # 环境变量配置 └── public/ ├── index.html # 登录页面 ├── profile.html # 用户信息页面 └── styles.css # 样式文件

状态: ✅ 配置完成,可以使用
访问地址: http://localhost:3000