OAuth 2.0 SSO 演示

体验完整的 OAuth 2.0 授权流程

OAuth 配置

可用权限: read, profile, email, write

流程说明

1

创建 OAuth 应用

管理后台 创建 OAuth 客户端,获取 Client ID

2

授权重定向

用户被重定向到授权页面进行登录和授权确认

3

获取授权码

用户授权后,系统重定向回应用并携带授权码

4

交换访问令牌

应用后端使用授权码交换访问令牌和刷新令牌

代码示例

// 1. 重定向到授权页面
const authUrl = new URL('/api/oauth/authorize');
authUrl.searchParams.set('client_id', 'client_52783a9e481f5fcefab4630ab4d0f9a1');
authUrl.searchParams.set('redirect_uri', 'http://localhost:3001/callback');
authUrl.searchParams.set('scope', 'read');
authUrl.searchParams.set('state', 'kwgfoa');

window.location.href = authUrl.toString();

// 2. 在回调页面交换令牌
const tokenResponse = await fetch('/api/oauth/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        grant_type: 'authorization_code',
        code: code, // 从回调URL获取
        redirect_uri: 'http://localhost:3001/callback',
        client_id: 'client_52783a9e481f5fcefab4630ab4d0f9a1',
        client_secret: 'your_client_secret'
    })
});

const tokens = await tokenResponse.json();

// 3. 使用访问令牌获取用户信息
const userResponse = await fetch('/api/oauth/userinfo', {
    headers: { 'Authorization': `Bearer ${tokens.access_token}` }
});

const user = await userResponse.json();

API 端点

授权端点

/api/oauth/authorize

令牌端点

/api/oauth/token

用户信息端点

/api/oauth/userinfo

令牌撤销端点

/api/oauth/revoke