iOS端使用expo-google-app-auth实现Google授权遇错误求助
问题解决与迁移方案
一、修复当前expo-google-app-auth 11.1.0的iOS授权问题
1. 清理无效配置
你的config里的permissions字段是Facebook授权专属配置,Google认证不需要该字段,直接删除即可:
const config = { androidClientId: "你的Android客户端ID", iosClientId: "你的iOS客户端ID", scopes: ['profile', 'email'], }
2. 检查原生依赖与项目配置
如果是裸React Native项目(已 eject 或用 expo prebuild 生成过原生代码):
- 进入iOS目录执行
pod install,确保expo-app-auth的Pod依赖正确安装,之后重新用Xcode构建项目。 - 确认GoogleService-Info.plist是通过Xcode添加到项目中的:打开Xcode,右键项目目录 → Add Files to "项目名",选中plist文件并勾选
Copy items if needed,确保目标项目已选中。 - 检查URL Scheme配置:打开Info.plist,找到
CFBundleURLTypes数组,添加一条CFBundleURLSchemes,值为GoogleService-Info.plist里的REVERSED_CLIENT_ID字段内容。
- 进入iOS目录执行
如果是Expo Managed项目:
- 在app.json的
ios.config.googleServicesFile字段指定GoogleService-Info.plist的路径,比如"./GoogleService-Info.plist",然后重新运行expo start --clear。
- 在app.json的
3. 完善错误捕获逻辑
修改signInWithGoogle函数,添加错误捕获以便排查问题:
const signInWithGoogle = async () => { try { const logInResult = await Google.logInAsync(config); if(logInResult.type === 'success'){ // 处理登录成功逻辑 } } catch (error) { console.error('Google登录错误:', error); } };
二、迁移到替代方案(expo-google-app-auth已废弃)
官方推荐使用expo-auth-session结合Google OAuth2端点实现认证,步骤如下:
1. 安装依赖
npx expo install expo-auth-session expo-crypto
2. 配置项目
在app.json中添加iOS的URL Scheme和权限配置:
{ "expo": { "ios": { "infoPlist": { "NSAppTransportSecurity": { "NSAllowsArbitraryLoads": true } }, "bundleIdentifier": "你的Bundle ID", "config": { "google": { "clientId": "你的iOS客户端ID", "reverseClientId": "你的REVERSED_CLIENT_ID" } } } } }
3. 重构登录代码
import React, { createContext, useContext } from 'react'; import * as AuthSession from 'expo-auth-session'; import * as WebBrowser from 'expo-web-browser'; WebBrowser.maybeCompleteAuthSession(); const AuthContext = createContext({}); const discovery = AuthSession.useAutoDiscovery('https://accounts.google.com'); export const AuthProvider = ({children}) => { const [request, response, promptAsync] = AuthSession.useAuthRequest( { clientId: "你的iOS客户端ID", scopes: ['profile', 'email'], redirectUri: AuthSession.makeRedirectUri({ useProxy: true }), }, discovery ); const signInWithGoogle = async () => { try { const result = await promptAsync(); if (result.type === 'success') { const { access_token } = result.params; // 用access_token获取用户信息 const userInfo = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', { headers: { Authorization: `Bearer ${access_token}` } }).then(res => res.json()); console.log('用户信息:', userInfo); } } catch (error) { console.error('登录错误:', error); } }; return ( <AuthContext.Provider value={{ user: null, signInWithGoogle }}> {children} </AuthContext.Provider> ); }; export default function useAuth() { return useContext(AuthContext); }
内容的提问来源于stack exchange,提问作者airjlee
相关产品推荐
相关产品推荐

