client_secret
curl -X POST https://api.aihubmix.com/api/oauth_apps \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_DEVELOPER_TOKEN" \
-d '{
"name": "我的第三方应用",
"description": "应用描述信息",
"redirect_uri": "https://yourapp.com/oauth/callback"
}'
{
"success": true,
"message": "应用创建成功",
"data": {
"id": 1,
"name": "我的第三方应用",
"client_id": "client_abc123def456...",
"client_secret": "secret_xyz789uvw012...",
"redirect_uri": "https://yourapp.com/oauth/callback",
"created_time": 1640995200
}
}
client_secret
只能在服务器端使用,绝不能暴露给浏览器function startLogin() {
// 重定向到您的服务器端授权处理端点
window.location.href = '/auth/oauth/start';
}
app.get('/auth/oauth/start', (req, res) => {
// 生成并存储state参数
const state = generateSecureRandomString();
req.session.oauth_state = state;
// 构建授权URL
const authUrl = new URL('https://your-domain.com/api/oauth2/authorize');
authUrl.searchParams.append('client_id', process.env.OAUTH_CLIENT_ID);
authUrl.searchParams.append('redirect_uri', process.env.OAUTH_REDIRECT_URI);
authUrl.searchParams.append('response_type', 'code');
authUrl.searchParams.append('scope', 'profile balance');
authUrl.searchParams.append('state', state);
authUrl.searchParams.append('auto_authorize', 'true'); // 一键登录
// 重定向到授权服务器
res.redirect(authUrl.toString());
});
app.get('/oauth/callback', async (req, res) => {
const { code, state, error } = req.query;
// 错误处理
if (error) {
return res.redirect(`/?error=${encodeURIComponent(error)}`);
}
// 参数验证
if (!code || !state) {
return res.redirect('/?error=missing_parameters');
}
// 验证state参数(防CSRF攻击)
if (state !== req.session.oauth_state) {
return res.redirect('/?error=invalid_state');
}
try {
// 用授权码换取访问令牌(在服务器端完成)
const tokenResponse = await fetch('https://your-domain.com/api/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code,
redirect_uri: process.env.OAUTH_REDIRECT_URI,
client_id: process.env.OAUTH_CLIENT_ID,
client_secret: process.env.OAUTH_CLIENT_SECRET // 只在服务器端使用
})
});
const tokenData = await tokenResponse.json();
if (!tokenResponse.ok) {
throw new Error(tokenData.error || 'Token exchange failed');
}
// 安全存储token(服务器端session或数据库)
req.session.access_token = tokenData.access_token;
req.session.refresh_token = tokenData.refresh_token;
req.session.token_expires_at = Date.now() + (tokenData.expires_in * 1000);
// 清理临时状态
delete req.session.oauth_state;
// 重定向到前端页面
res.redirect('/?login=success');
} catch (error) {
console.error('OAuth callback error:', error);
res.redirect(`/?error=server_error`);
}
});
async function loadUserInfo() {
try {
const response = await fetch('/api/user/info');
if (!response.ok) {
throw new Error('Failed to fetch user info');
}
const userInfo = await response.json();
displayUserInfo(userInfo);
} catch (error) {
console.error('Failed to load user info:', error);
showLoginButton();
}
}
app.get('/api/user/info', async (req, res) => {
const accessToken = req.session.access_token;
if (!accessToken) {
return res.status(401).json({ error: 'Not authenticated' });
}
try {
// 代理请求到OAuth服务器
const response = await fetch('https://your-domain.com/api/oauth2/userinfo', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
if (!response.ok) {
throw new Error('User info request failed');
}
const userInfo = await response.json();
res.json(userInfo);
} catch (error) {
console.error('User info proxy error:', error);
res.status(500).json({ error: 'Server error' });
}
});
/api/oauth2/authorize
引导用户进行 OAuth2 授权。
参数:
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
client_id | string | 是 | 应用的客户端ID(可在前端使用) |
redirect_uri | string | 是 | 授权后的回调地址(必须指向服务器端点) |
response_type | string | 是 | 固定值:code |
scope | string | 否 | 权限范围,多个用空格分隔 |
state | string | 必填 | 防CSRF攻击的随机字符串(服务器端生成) |
auto_authorize | string | 否 | 设为 true 时启用自动授权 |
redirect_uri
必须与注册时的地址完全匹配state
参数必须是服务器端生成的随机字符串profile
:获取用户基本信息(用户名、邮箱)balance
:获取用户账户余额信息/api/oauth2/token
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
grant_type | string | 是 | 固定值:authorization_code |
code | string | 是 | 授权码 |
redirect_uri | string | 是 | 必须与授权时的地址一致 |
client_id | string | 是 | 应用的客户端 ID |
client_secret | string | 是 | 应用的客户端密钥(只能在服务器端使用) |
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
grant_type | string | 是 | 固定值:refresh_token |
refresh_token | string | 是 | 刷新令牌 |
client_id | string | 是 | 应用的客户端ID |
client_secret | string | 是 | 应用的客户端密钥(只能在服务器端使用) |
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 7200,
"refresh_token": "refresh_abc123def456...",
"scope": "profile balance"
}
/api/oauth2/userinfo
获取用户基本信息和账户余额。
请求头:
Authorization: Bearer {access_token}
{
"id": 12345,
"username": "user123",
"email": "user@example.com",
"quota": 1000000,
"used_quota": 250000,
"balance_formatted": "750.00",
"created_time": 1640995200,
"status": 1
}
<!DOCTYPE html>
<html>
<head>
<title>第三方应用示例</title>
<style>
.container { max-width: 800px; margin: 0 auto; padding: 20px; }
.user-info { background: #f5f5f5; padding: 20px; border-radius: 8px; margin: 20px 0; }
.login-section { text-align: center; padding: 40px; }
.btn { padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; }
.btn-primary { background: #007bff; color: white; }
.btn-success { background: #28a745; color: white; }
.btn-secondary { background: #6c757d; color: white; }
.hidden { display: none; }
</style>
</head>
<body>
<div class="container">
<h1>我的第三方应用</h1>
<!-- 加载状态 -->
<div id="loading">
<p>检查登录状态中...</p>
</div>
<!-- 已登录用户信息 -->
<div id="user-info" class="user-info hidden">
<h2>欢迎回来!</h2>
<p><strong>用户名:</strong><span id="username"></span></p>
<p><strong>邮箱:</strong><span id="email"></span></p>
<p><strong>账户余额:</strong><span id="balance"></span></p>
<div style="margin-top: 20px;">
<button class="btn btn-success" onclick="refreshBalance()">刷新余额</button>
<button class="btn btn-primary" onclick="goToTopup()">账户充值</button>
<button class="btn btn-secondary" onclick="logout()">退出登录</button>
</div>
</div>
<!-- 未登录状态 -->
<div id="login-section" class="login-section hidden">
<h2>请登录以查看账户信息</h2>
<p>使用一键登录快速访问您的账户</p>
<button class="btn btn-primary" onclick="oneClickLogin()">
🚀 一键登录
</button>
</div>
</div>
<script>
// OAuth配置
const OAUTH_CONFIG = {
authServer: 'https://your-domain.com',
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET', // 生产环境应该在后端处理
redirectUri: window.location.origin + '/oauth/callback.html',
scope: 'profile balance'
};
class OAuthManager {
constructor() {
this.accessToken = localStorage.getItem('oauth_access_token');
this.refreshToken = localStorage.getItem('oauth_refresh_token');
this.tokenExpiresAt = localStorage.getItem('oauth_token_expires_at');
this.isRefreshing = false; // 防止并发刷新
this.init();
}
async init() {
// 检查URL中是否有授权码
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
if (code) {
await this.handleAuthCallback(code, state);
// 清理URL
window.history.replaceState({}, document.title, window.location.pathname);
} else if (this.accessToken) {
try {
// 检查token是否过期,如果过期尝试刷新
if (this.isTokenExpired()) {
await this.refreshTokenIfNeeded();
}
await this.fetchUserInfo();
this.showUserInfo();
} catch (error) {
console.log('Token可能已过期或无效,需要重新登录');
this.clearTokens();
this.showLoginSection();
}
} else {
this.showLoginSection();
}
document.getElementById('loading').classList.add('hidden');
}
// 检查access token是否过期
isTokenExpired() {
if (!this.tokenExpiresAt) return false;
const expiryTime = parseInt(this.tokenExpiresAt);
const bufferTime = 5 * 60 * 1000; // 5分钟缓冲时间
return Date.now() > (expiryTime - bufferTime);
}
// 自动刷新token
async refreshTokenIfNeeded() {
if (!this.refreshToken || this.isRefreshing) {
return false;
}
this.isRefreshing = true;
try {
const response = await fetch(`${OAUTH_CONFIG.authServer}/api/oauth2/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: this.refreshToken,
client_id: OAUTH_CONFIG.clientId,
client_secret: OAUTH_CONFIG.clientSecret,
})
});
if (response.ok) {
const tokenData = await response.json();
this.updateTokens(tokenData);
return true;
} else {
throw new Error('Token refresh failed');
}
} catch (error) {
console.error('刷新token失败:', error);
this.clearTokens();
return false;
} finally {
this.isRefreshing = false;
}
}
// 更新token信息
updateTokens(tokenData) {
this.accessToken = tokenData.access_token;
this.refreshToken = tokenData.refresh_token;
this.tokenExpiresAt = Date.now() + (tokenData.expires_in * 1000);
localStorage.setItem('oauth_access_token', this.accessToken);
localStorage.setItem('oauth_refresh_token', this.refreshToken);
localStorage.setItem('oauth_token_expires_at', this.tokenExpiresAt.toString());
}
oneClickLogin() {
const state = this.generateState();
localStorage.setItem('oauth_state', state);
const authUrl = `${OAUTH_CONFIG.authServer}/api/oauth2/authorize?` +
`client_id=${OAUTH_CONFIG.clientId}&` +
`redirect_uri=${encodeURIComponent(OAUTH_CONFIG.redirectUri)}&` +
`response_type=code&` +
`scope=${encodeURIComponent(OAUTH_CONFIG.scope)}&` +
`state=${state}&` +
`auto_authorize=true`; // 启用自动授权,实现真正的一键登录
// 在弹窗中打开授权页面
const popup = window.open(authUrl, 'oauth_login', 'width=500,height=600,scrollbars=yes');
// 监听弹窗关闭
const checkClosed = setInterval(() => {
if (popup.closed) {
clearInterval(checkClosed);
// 检查是否获得了授权
setTimeout(() => this.init(), 1000);
}
}, 1000);
}
async handleAuthCallback(code, state) {
const savedState = localStorage.getItem('oauth_state');
if (state !== savedState) {
console.error('State参数不匹配');
return;
}
try {
const response = await fetch(`${OAUTH_CONFIG.authServer}/api/oauth2/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code,
client_id: OAUTH_CONFIG.clientId,
client_secret: OAUTH_CONFIG.clientSecret,
redirect_uri: OAUTH_CONFIG.redirectUri
})
});
const tokenData = await response.json();
if (tokenData.access_token) {
this.updateTokens(tokenData);
localStorage.removeItem('oauth_state');
await this.fetchUserInfo();
this.showUserInfo();
}
} catch (error) {
console.error('获取访问令牌失败:', error);
}
}
// 带自动刷新的API请求方法
async apiRequest(url, options = {}) {
// 检查并刷新token
if (this.isTokenExpired()) {
const refreshed = await this.refreshTokenIfNeeded();
if (!refreshed) {
throw new Error('Unable to refresh token');
}
}
const headers = {
'Authorization': `Bearer ${this.accessToken}`,
...options.headers
};
const response = await fetch(url, {
...options,
headers
});
// 如果收到401错误,尝试刷新token并重试一次
if (response.status === 401 && !options._retry) {
const refreshed = await this.refreshTokenIfNeeded();
if (refreshed) {
return this.apiRequest(url, { ...options, _retry: true });
}
}
return response;
}
async fetchUserInfo() {
const response = await this.apiRequest(`${OAUTH_CONFIG.authServer}/api/oauth2/userinfo`);
if (!response.ok) {
throw new Error('获取用户信息失败');
}
this.userInfo = await response.json();
}
showUserInfo() {
document.getElementById('username').textContent = this.userInfo.username;
document.getElementById('email').textContent = this.userInfo.email;
document.getElementById('balance').textContent = this.userInfo.balance_formatted;
document.getElementById('user-info').classList.remove('hidden');
document.getElementById('login-section').classList.add('hidden');
}
showLoginSection() {
document.getElementById('user-info').classList.add('hidden');
document.getElementById('login-section').classList.remove('hidden');
}
async refreshBalance() {
try {
await this.fetchUserInfo();
document.getElementById('balance').textContent = this.userInfo.balance_formatted;
alert('余额已更新');
} catch (error) {
alert('刷新失败,请重新登录');
this.clearTokens();
this.showLoginSection();
}
}
async goToTopup() {
try {
const response = await this.apiRequest(`${OAUTH_CONFIG.authServer}/api/oauth2/topup`);
const data = await response.json();
if (data.topup_url) {
window.open(data.topup_url, '_blank');
}
} catch (error) {
console.error('获取充值链接失败:', error);
}
}
logout() {
this.clearTokens();
this.showLoginSection();
}
clearTokens() {
this.accessToken = null;
this.refreshToken = null;
this.tokenExpiresAt = null;
this.userInfo = null;
localStorage.removeItem('oauth_access_token');
localStorage.removeItem('oauth_refresh_token');
localStorage.removeItem('oauth_token_expires_at');
}
generateState() {
return Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15);
}
}
// 全局函数
let oauthManager;
function oneClickLogin() {
oauthManager.oneClickLogin();
}
function refreshBalance() {
oauthManager.refreshBalance();
}
function goToTopup() {
oauthManager.goToTopup();
}
function logout() {
oauthManager.logout();
}
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
oauthManager = new OAuthManager();
});
</script>
</body>
</html>
/oauth/callback.html
文件:
<!DOCTYPE html>
<html>
<head>
<title>登录处理中...</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
.loading { color: #666; }
.error { color: #dc3545; }
</style>
</head>
<body>
<h2>登录处理中,请稍候...</h2>
<div id="status" class="loading">正在验证授权信息...</div>
<script>
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
const error = urlParams.get('error');
if (error) {
document.getElementById('status').innerHTML =
`<div class="error">授权失败: ${error}</div>`;
setTimeout(() => {
if (window.opener) {
window.close();
} else {
window.location.href = '/';
}
}, 3000);
} else if (code) {
if (window.opener) {
// 如果是弹窗,关闭并让父窗口处理
window.opener.location.href =
window.opener.location.pathname + `?code=${code}&state=${state}`;
window.close();
} else {
// 如果不是弹窗,重定向到主页面
window.location.href = `/?code=${code}&state=${state}`;
}
} else {
document.getElementById('status').innerHTML =
'<div class="error">未收到有效的授权信息</div>';
setTimeout(() => {
window.location.href = '/';
}, 3000);
}
</script>
</body>
</html>
client_secret
:
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const app = express();
app.use(cors());
app.use(express.json());
const OAUTH_CONFIG = {
authServer: 'https://your-domain.com',
clientId: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET'
};
// 后端处理token交换
app.post('/api/oauth/exchange-token', async (req, res) => {
const { code, redirectUri, state } = req.body;
try {
const response = await fetch(`${OAUTH_CONFIG.authServer}/api/oauth2/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code,
client_id: OAUTH_CONFIG.clientId,
client_secret: OAUTH_CONFIG.clientSecret,
redirect_uri: redirectUri
})
});
const tokenData = await response.json();
if (response.ok) {
res.json(tokenData);
} else {
res.status(400).json(tokenData);
}
} catch (error) {
res.status(500).json({ error: 'Token exchange failed' });
}
});
// 刷新token端点
app.post('/api/oauth/refresh-token', async (req, res) => {
const { refreshToken } = req.body;
if (!refreshToken) {
return res.status(400).json({ error: 'Missing refresh token' });
}
try {
const response = await fetch(`${OAUTH_CONFIG.authServer}/api/oauth2/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: OAUTH_CONFIG.clientId,
client_secret: OAUTH_CONFIG.clientSecret,
})
});
const tokenData = await response.json();
if (response.ok) {
res.json(tokenData);
} else {
res.status(400).json(tokenData);
}
} catch (error) {
res.status(500).json({ error: 'Token refresh failed' });
}
});
// 代理用户信息请求(带自动刷新)
app.get('/api/oauth/userinfo', async (req, res) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: 'Missing authorization header' });
}
try {
const response = await fetch(`${OAUTH_CONFIG.authServer}/api/oauth2/userinfo`, {
headers: {
'Authorization': authHeader
}
});
const userData = await response.json();
if (response.ok) {
res.json(userData);
} else {
res.status(response.status).json(userData);
}
} catch (error) {
res.status(500).json({ error: 'Failed to fetch user info' });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
client_secret
存储在后端服务器client_secret
// 生成随机state
const state = crypto.randomBytes(16).toString('hex');
localStorage.setItem('oauth_state', state);
// 验证state
const savedState = localStorage.getItem('oauth_state');
if (receivedState !== savedState) {
throw new Error('CSRF attack detected');
}
HTTPS
HTTPS
HTTPS
// 设置 token 过期时间
const expiryTime = Date.now() + (tokenData.expires_in * 1000);
localStorage.setItem('oauth_token_expiry', expiryTime);
// 检查token是否过期
function isTokenExpired() {
const expiry = localStorage.getItem('oauth_token_expiry');
return !expiry || Date.now() > parseInt(expiry);
}
try {
const response = await fetch('/api/oauth2/userinfo', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (!response.ok) {
if (response.status === 401) {
// Token过期,需要重新登录
clearToken();
showLoginSection();
} else {
throw new Error(`HTTP ${response.status}`);
}
}
const userInfo = await response.json();
return userInfo;
} catch (error) {
console.error('API request failed:', error);
// 处理网络错误等
}
auto_authorize=true
参数即可。这样用户登录完成后会自动完成授权,无需额外的确认步骤:
const authUrl = 'https://your-domain.com/api/oauth2/authorize?' +
'client_id=YOUR_CLIENT_ID&' +
'auto_authorize=true&' + // 关键参数
'...其他参数';
// SDK 会自动处理 token 刷新,您无需手动处理
const userInfo = await oauthManager.fetchUserInfo(); // 自动刷新token
profile
scope: 用户名、邮箱balance
scope: 账户余额信息HTTP localhost
进行测试