OAuth 2.0授权码流程通过前端重定向获取code,后端用code换取token,确保第三方应用安全访问用户资源而不暴露密码。
OAuth 是一种开放标准,允许用户在不暴露密码的情况下授权第三方应用访问其资源。在 JavaScript 中实现 OAuth 认证流程,通常用于前端应用(如 React、Vue)与后端服务或第三方平台(如 GitHub、Google、Facebook)集成。以下是基于 OAuth 2.0 授权码流程的典型实现方式。
这是最安全且常用的 OAuth 流程,适用于有后端的应用:
构建授权 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 类似:
https://yourapp.com/auth/callback?code=AUTHORIZATION_CODE
在回调页面提取 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: '认证失败' });
}
});
确保实现过程安全可靠: