React Web应用结合Cognito实现Google One Tap登录方法
React + Cognito 实现Google One Tap登录方案
注:旧版Google Sign-In JavaScript Platform Library已于2023年3月31日正式停用,所有新开发必须使用新版Google Identity Services SDK对接。
前置准备
- 在Google云控制台创建OAuth 2.0 Web类型客户端,将应用域名加入授权JS来源列表,保存生成的客户端ID备用
- 在Cognito用户池内添加Google身份提供商,填入对应Google客户端ID、密钥,配置好授权回调地址
代码实现
不需要安装额外第三方依赖,直接动态加载官方GSI SDK即可,先封装SDK加载hook:
import { useEffect, useState } from 'react'; // 动态加载Google Identity Services脚本 export const useLoadGsiScript = () => { const [scriptReady, setScriptReady] = useState(false); useEffect(() => { const existingScript = document.querySelector('script[src="https://accounts.google.com/gsi/client"]'); if (existingScript) { setScriptReady(true); return; } const scriptEl = document.createElement('script'); scriptEl.src = 'https://accounts.google.com/gsi/client'; scriptEl.async = true; scriptEl.defer = true; scriptEl.onload = () => setScriptReady(true); document.body.appendChild(scriptEl); }, []); return scriptReady; };
再封装One Tap登录组件,拿到Google返回的凭证后直接对接Cognito联邦登录:
import { useEffect } from 'react'; import { useLoadGsiScript } from './useLoadGsiScript'; import { Auth } from 'aws-amplify'; // 如使用Amplify对接Cognito可直接用,否则可自行调用Cognito相关API const GoogleOneTap = () => { const gsiReady = useLoadGsiScript(); // 处理Google返回的登录凭证 const handleCredentialResponse = async (res) => { const googleIdToken = res.credential; try { // 提交ID Token到Cognito完成联邦登录 await Auth.federatedSignIn('google', { token: googleIdToken }); // 登录成功后自行处理路由跳转、用户状态同步即可 } catch (err) { console.error('Cognito联邦登录失败:', err); } }; useEffect(() => { if (!gsiReady || !window.google) return; // 初始化One Tap配置 window.google.accounts.id.initialize({ client_id: '替换为你自己的Google OAuth客户端ID', callback: handleCredentialResponse, auto_select: false, // 已授权用户可开启自动登录 cancel_on_tap_outside: true, }); // 唤起One Tap弹窗 window.google.accounts.id.prompt((notify) => { if (notify.isNotDisplayed() || notify.isSkippedMoment()) { // 可在此处处理弹窗被拦截、冷却期不展示的逻辑 return; } }); return () => { window.google?.accounts.id.cancel(); }; }, [gsiReady]); return null; }; export default GoogleOneTap;
在应用登录页、首页等需要唤起One Tap的位置直接引入该组件即可。如果需要渲染固定的Google登录按钮,可在SDK加载完成后调用window.google.accounts.id.renderButton方法,将按钮渲染到指定DOM节点,支持自定义尺寸、主题、文案。
常见问题说明
- 不要复用旧版gapi库的登录逻辑:旧版接口已完全停用,调用会直接返回权限错误
- One Tap弹窗不展示是正常现象:如果用户多次手动关闭弹窗,Google侧会触发冷却期,冷却期内不会主动弹出,属于官方默认风控策略
- Cognito侧配置校验:确保Cognito内Google身份提供商填写的客户端ID和前端使用的ID完全一致,否则会出现ID Token校验失败问题
- 跨域问题:本地调试时要把localhost加入Google OAuth客户端的授权来源列表,否则SDK不会发起弹窗
功能效果参考:
内容的提问来源于stack exchange,提问作者ashen madusanka
相关产品推荐
相关产品推荐

