如何用gapi-script获取可换取access/refresh token的授权code
原生gapi-script实现Google授权码模式获取code
前置配置(Google Cloud控制台)
- 确保你的OAuth 2.0客户端ID为Web应用类型
- 在「已授权的重定向URI」中添加前端回调地址(例:
http://localhost:3000/login) - 客户端需支持离线访问(后续代码中通过
access_type=offline配置)
React代码实现步骤
1. 加载并初始化gapi
通过useEffect在组件挂载时完成gapi加载与授权客户端初始化:
import { useEffect, useState } from 'react'; import { loadGapiInsideDOM } from 'gapi-script'; const GoogleAuth = () => { const [gapiLoaded, setGapiLoaded] = useState(false); useEffect(() => { const initGapi = async () => { await loadGapiInsideDOM(); window.gapi.load('auth2', () => { window.gapi.auth2.init({ client_id: '你的Google客户端ID', scope: 'email profile', // 根据业务需求添加权限 access_type: 'offline', // 必须配置,用于获取refresh_token response_type: 'code', // 指定返回授权码而非直接返回access_token redirect_uri: '你的前端回调地址' // 需与控制台配置完全一致 }).then(() => setGapiLoaded(true)); }); }; initGapi(); }, []);
2. 触发授权并获取code
添加登录按钮,点击后触发授权流程,提取code并发送至后端:
const handleGoogleLogin = () => { if (!gapiLoaded) return; const authInstance = window.gapi.auth2.getAuthInstance(); authInstance.signIn({ prompt: 'consent', // 首次授权强制弹窗,确保能拿到refresh_token;非首次可改为'none' response_type: 'code' // 再次明确返回类型 }).then(googleUser => { // 从授权响应中提取code const authResponse = googleUser.getAuthResponse(); const authCode = authResponse.code; // 将code发送至后端接口换取token fetch('/api/google/exchange-token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: authCode }) }).then(res => res.json()) .then(data => { // 处理后端返回的access_token、refresh_token console.log('后端返回令牌:', data); }) .catch(err => console.error('发送code失败:', err)); }).catch(err => console.error('授权失败:', err)); }; return ( <div> {gapiLoaded && <button onClick={handleGoogleLogin}>Google登录</button>} </div> ); }; export default GoogleAuth;
核心改动说明
- 初始化auth2时新增
response_type: 'code',指定返回授权码而非直接返回access_token - 配置
access_type: 'offline',确保后端能获取refresh_token用于令牌刷新 - 从授权响应中提取
code字段,替代原来直接获取的access_token - 将code通过POST请求发送至后端,由后端完成与Google令牌接口的交互
后端补充说明
后端需用收到的code,结合以下参数向https://oauth2.googleapis.com/token发送POST请求:
code: 前端传来的授权码client_id: Google客户端IDclient_secret: Google客户端密钥(仅后端保存,禁止暴露在前端)redirect_uri: 与前端配置一致的回调地址grant_type:authorization_code
请求成功后,Google会返回包含access_token、refresh_token、expires_in的响应,后端可根据业务需求处理这些令牌。
内容的提问来源于stack exchange,提问作者Alexander Solonik
相关产品推荐
相关产品推荐

