使用expo-auth-session实现Google登录时Android重定向URI问题
Expo托管工作流中expo-auth-session Android端Google登录重定向URI问题解决
问题描述
使用Expo托管工作流,通过expo-auth-session实现Google登录,iOS和Web端功能正常,但Android端触发Error 400: invalid_request,报错指向redirect_uri=com.googleusercontent.apps.[ANDROID-ID]。
当前重定向URI构造代码:
// a helper to reverse client ids const reverseClientId = (clientId) => clientId.split('.').reverse().join('.'); // redirect Uri generator, where I suspect the problem is const redirectUri = Platform.select({ ios: reverseClientId(config.authKeys.ios), android: reverseClientId(config.authKeys.android), web: window?.location?.origin, }) + Platform.select({ ios: ":/oauth2redirect/google", android: "", web: "" }); // usage of the redirecUri with the AuthSession.AuthRequest const createAuthRequest = async () => { return new AuthSession.AuthRequest({ redirectUri // other params }); };
相关配置:
config.authKeys:
{ "android": "[ANDROID-ID].apps.googleusercontent.com", "ios": "[IOS-ID].apps.googleusercontent.com", "web": "[WEB-ID].apps.googleusercontent.com" }
- Google Cloud Console配置:
- 包名:与app.json中
expo.android.package字段一致 - Client ID:
[ANDROID-ID].apps.googleusercontent.com
- 包名:与app.json中
解决方案
1. 替换手动构造重定向URI的方式
不要通过反转Client ID生成重定向URI,改用expo-auth-session内置的AuthSession.makeRedirectUri()方法,它会自动适配Expo托管工作流的平台规则:
import * as AuthSession from 'expo-auth-session'; // 自动生成符合要求的重定向URI const redirectUri = AuthSession.makeRedirectUri({ useProxy: false, // 托管工作流下保持此配置即可 }); const createAuthRequest = async () => { return new AuthSession.AuthRequest({ redirectUri, clientId: config.authKeys.android, scopes: ['openid', 'profile', 'email'], // 根据业务需求添加权限 // 其他必要参数(如responseType等)按需配置 }); };
2. 完善Google Cloud Console配置
- 添加SHA-1指纹:执行
expo fetch:android:hashes命令,获取Expo托管应用的SHA-1和SHA-256指纹,将SHA-1添加到Google Cloud对应Android客户端的「签名证书指纹」区域。 - 配置重定向URI:将
AuthSession.makeRedirectUri()生成的URI(格式通常为exp://<你的Expo项目slug>.exp.direct/google/auth)添加到Google Cloud对应Android客户端的「授权重定向URI」列表中。
3. 验证app.json配置
确保app.json中的expo.android.package字段与Google Cloud配置的包名完全一致,托管工作流下无需手动设置scheme字段,Expo会自动处理。
内容的提问来源于stack exchange,提问作者Mehmet Kaplan
相关产品推荐
相关产品推荐

