Expo集成Google登录时response.authentication为null的原因排查
问题原因与解决方案
核心原因
你使用的Google.useIdTokenAuthRequest是专门用于获取**ID令牌(ID Token)**的API,它不会返回访问令牌(Access Token),所以response.authentication会是null,这是该API的设计特性。
解决步骤
替换API为
useAuthRequest
要获取访问令牌,需使用Google.useAuthRequest——这个API会请求OAuth 2.0授权码,进而交换得到访问令牌。修改初始化代码如下:const [request, response, promptAsync] = Google.useAuthRequest({ expoClientId: "[REDACTED].apps.googleusercontent.com", webClientId: "[REDACTED].apps.googleusercontent.com", iosClientId: "[REDACTED].apps.googleusercontent.com", androidClientId: "[REDACTED].apps.googleusercontent.com", // 必须添加必要的权限范围 scopes: ["openid", "profile", "email"], });修复useEffect逻辑问题
你当前代码中,setAccessToken后立刻使用accessToken调用fetchUserInfo无效——因为useState更新是异步的,此时accessToken仍是旧值。应直接用response中的令牌调用:React.useEffect(() => { if (response?.type === "success") { const { accessToken } = response.authentication; console.log("访问令牌:", accessToken); setAccessToken(accessToken); // 直接用获取到的accessToken调用接口 fetchUserInfo(accessToken); } }, [response]);验证Google Cloud配置
确保在Google Cloud控制台中:- 已为对应平台(Android/iOS/Web)正确配置OAuth客户端ID
- 已将Expo的回调URL添加到授权重定向URI列表(开发环境格式通常为
https://auth.expo.io/@你的用户名/你的项目slug)
内容的提问来源于stack exchange,提问作者Blake Liu
相关产品推荐
相关产品推荐

