OAuth 2.0授权码流程通过前端重定向获取code,后端用code换取token,确保第三方应用安全访问用户资源而不暴露密码。

OAuth 是一种开放标准,允许用户在不暴露密码的情况下授权第三方应用访问其资源。在 JavaScript 中实现 OAuth 认证流程,通常用于前端应用(如 React、Vue)与后端服务或第三方平台(如 GitHub、Google、Facebook)集成。以下是基于 OAuth 2.0 授权码流程的典型实现方式。
理解 OAuth 2.0 授权码流程
这是最安全且常用的 OAuth 流程,适用于有后端的应用:
- 应用将用户重定向到授权服务器(如 Google 登录页)
- 用户登录并同意授权
- 授权服务器回调你的应用指定的 redirect_uri,并附带一个临时的 code
- 前端将 code 发送给后端
- 后端使用 code、client_id、client_secret 向授权服务器请求 access_token
- 获取 token 后,后端可调用第三方 API 代表用户操作
前端跳转授权页面
构建授权 URL 并跳转:
const clientId = 'your_client_id';
const redirectUri = encodeURIComponent('https://yourapp.com/auth/callback');
const scope = encodeURIComponent('email profile');
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?
client_id=${clientId}&
redirect_uri=${redirectUri}&
response_type=code&
scope=${scope}&
access_type=offline&
prompt=consent`;
// 跳转
window.location.href = authUrl;
用户授权后会跳回 redirect_uri,URL 类似:
立即学习“Java免费学习笔记(深入)”;
https://yourapp.com/auth/callback?code=AUTHORIZATION_CODE
处理回调并交换 Token
在回调页面提取 code,并发送给后端:
// 从 URL 获取 code
function getUrlParam(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name);
}
const code = getUrlParam('code');
if (code) {
// 发送 code 到自己的后端
fetch('/api/auth/google/callback', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code })
})
.then(res => res.json())
.then(data => {
console.log('登录成功', data);
// 存储 token 或跳转主页
});
}
后端示例(Node.js + Express):
const axios = require('axios');
app.post('/api/auth/google/callback', async (req, res) => {
const { code } = req.body;
try {
const tokenResponse = await axios.post('https://oauth2.googleapis.com/token', null, {
params: {
client_id: 'your_client_id',
client_secret: 'your_client_secret',
code,
redirect_uri: 'https://yourapp.com/auth/callback',
grant_type: 'authorization_code'
}
});
const { access_token, id_token } = tokenResponse.data;
// 可选:验证 id_token(JWT)
// 使用 access_token 请求用户信息
const userResponse = await axios.get('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: { Authorization: `Bearer ${access_token}` }
});
const user = userResponse.data;
// 创建本地会话或返回 JWT
res.json({ user, access_token });
} catch (err) {
res.status(400).json({ error: '认证失败' });
}
});
安全建议与最佳实践
确保实现过程安全可靠:
- 始终使用 HTTPS,防止 code 或 token 被窃取
- 设置合理的 redirect_uri 白名单
- 避免在前端暴露 client_secret
- 对返回的 JWT token 进行校验(如 Google 的 id_token)
- 使用短生命周期的 access_token,配合 refresh_token 自动刷新
- SPA 应启用 PKCE 防止授权码拦截攻击










