如何获取Google登录(Sign In With Google)的Refresh Token
获取Google GSI的Refresh Token解决方案
Google Identity Services (GSI)的前端One Tap/登录按钮默认不会返回Refresh Token——因为前端环境无法安全存储Refresh Token,官方要求通过**授权码流程(带PKCE)**在后端获取。
具体操作步骤:
- 初始化GSI时,必须添加
scope: "openid email profile offline_access",其中offline_access是获取Refresh Token的核心权限;同时配置ux_mode为"redirect"或"popup"(推荐redirect避免弹窗拦截)。 - 前端拿到授权码后,将其发送到你的后端服务,由后端调用Google的令牌端点,交换得到Access Token和Refresh Token。
- 后端安全存储Refresh Token,后续当Access Token过期时,用Refresh Token向Google申请新的Access Token。
修改后的前端代码示例:
window.onload = function () { google.accounts.id.initialize({ client_id: "你的客户端ID", callback: handleCredentialResponse, scope: "openid email profile offline_access", ux_mode: "redirect", redirect_uri: "你的后端回调地址" // 需在Google Cloud控制台配置 }); google.accounts.id.renderButton( document.getElementById("google-signin-button"), { theme: "outline", size: "large", shape: "circle" } ); google.accounts.id.prompt(); }; function handleCredentialResponse(response) { // 若用redirect模式,授权码会在URL的code参数里,直接跳转后端处理即可 // 若用popup模式,response.code就是授权码,发送到后端 if (response.code) { fetch('/your-backend-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: response.code }) }); } }
后端核心逻辑(伪代码):
# 示例用Python,其他语言逻辑一致 import requests def exchange_authorization_code(code): token_endpoint = "https://oauth2.googleapis.com/token" payload = { "client_id": "你的客户端ID", "client_secret": "你的客户端密钥", "code": code, "grant_type": "authorization_code", "redirect_uri": "你的后端回调地址" } response = requests.post(token_endpoint, data=payload) token_data = response.json() # 此处可获取到access_token、refresh_token、expires_in等字段 refresh_token = token_data.get("refresh_token") # 将refresh_token安全存储到数据库或密钥管理服务中
注意事项:
offline_access权限必须明确声明,否则Google不会返回Refresh Token。- 后端回调地址必须在Google Cloud控制台的OAuth 2.0客户端ID配置中,添加到"已授权的重定向URI"列表内。
- Refresh Token仅在用户首次授权时返回一次(除非用户重新授权或配置
prompt: "consent"强制触发授权确认),因此后端务必妥善存储。
内容的提问来源于stack exchange,提问作者brohxa
相关产品推荐
相关产品推荐

