如何将Cognito用户池Google身份提供商集成到React Native iOS应用
实现React Native iOS集成AWS Cognito Google登录步骤
一、前置确认
- 确保AWS Cognito用户池已启用Google身份提供商,且回调URL配置正确(需包含React Native iOS应用的自定义URL scheme,比如
com.yourappname://oauth2redirect) - 确认Google Cloud Console中对应OAuth 2.0客户端ID已添加上述自定义URL scheme到授权重定向URI列表
二、安装依赖
使用AWS官方的Amplify库来集成Cognito认证:
npm install @aws-amplify/react-native aws-amplify # 或用yarn yarn add @aws-amplify/react-native aws-amplify
安装iOS原生依赖:
cd ios && pod install && cd ..
三、iOS项目配置
- 打开Xcode,编辑项目的
Info.plist(右键选择Open As->Source Code),添加自定义URL scheme:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>com.yourappname</string> <!-- 替换为你的应用Bundle ID --> </array> </dict> </array>
- 若需要跨域请求,在
Info.plist添加ATS配置:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
四、初始化AWS Amplify
在项目入口文件(如App.js)中初始化配置:
import Amplify from 'aws-amplify'; import awsConfig from './aws-exports'; Amplify.configure(awsConfig);
如果没有自动生成的aws-exports.js,可手动编写核心配置:
export default { Auth: { region: '你的AWS区域', userPoolId: '你的用户池ID', userPoolWebClientId: '你的用户池客户端ID', oauth: { domain: '你的Cognito托管UI域名(如xxx.auth.us-east-1.amazoncognito.com)', scope: ['email', 'openid', 'profile'], redirectSignIn: 'com.yourappname://oauth2redirect', redirectSignOut: 'com.yourappname://oauth2redirect', responseType: 'code' } } };
五、实现Google登录按钮
创建登录组件,调用Amplify的联邦登录方法:
import React from 'react'; import { TouchableOpacity, Text, StyleSheet } from 'react-native'; import { Auth } from 'aws-amplify'; const GoogleLoginButton = () => { const handleLogin = async () => { try { const user = await Auth.federatedSignIn({ provider: 'Google' }); // 登录成功后,用户数据会自动同步到Cognito用户池 console.log('登录成功:', user); } catch (err) { console.error('登录失败:', err); } }; return ( <TouchableOpacity style={styles.button} onPress={handleLogin}> <Text style={styles.buttonText}>用Google登录</Text> </TouchableOpacity> ); }; const styles = StyleSheet.create({ button: { paddingVertical: 12, paddingHorizontal: 24, backgroundColor: '#4285F4', borderRadius: 4, alignItems: 'center' }, buttonText: { color: '#fff', fontWeight: '600', fontSize: 16 } }); export default GoogleLoginButton;
六、处理登录回调
在iOS项目的AppDelegate.m中添加URL回调处理,确保登录后能返回应用:
#import <React/RCTLinkingManager.h> - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [RCTLinkingManager application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; } // iOS 9及以上版本需补充 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options { return [RCTLinkingManager application:application openURL:url options:options]; }
七、验证用户同步
登录成功后,进入AWS Cognito用户池控制台,选择「用户和组」,即可看到通过Google登录创建的用户,用户信息会同步Google返回的邮箱、姓名等字段。
内容的提问来源于stack exchange,提问作者Ayush Vishwakarma
相关产品推荐
相关产品推荐

