How to implement Google Signin with existing User Pool and Identity Pool into React Native app?
Google Side
Create 3 Google OAuth Client Ids
- One is “Web application” type
https://aws-amplify.github.io/docs/js/cognito-hosted-ui-federated-identity#google-sign-in-instructions - One is “iOS” type
- One is “Android” type
AWS Side
Create AWS Open ID Provider in AIM connecting with “iOS” and “Android” client IDs
- Provider URL as “https://accounts.google.com”
- Audience with Google iOS Client ID and Google Android Client ID
Create AWS Amplify User Pool, App Client & Identity Pool
- Create User Pool
- Create and connect client app to user Pool
- Create new Federated Identity Pool
- Apply “Authentication Provider” with “OpenID” as “accounts.google.com” checked
React Native side – Implement Google Signin
Create “aws-exports.js” file
const config = {
identityPoolId: '', // from Federated Identities
region: '',
userPoolId: '',
userPoolWebClientId: ''
}
export default config
Add “react-native-community/google-signin” dependencies for iOS and Android
Build Google Signin button
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React from 'react';
import {SafeAreaView, StyleSheet, Button, StatusBar} from 'react-native';
import Amplify, {Auth} from 'aws-amplify';
import {GoogleSignin} from '@react-native-community/google-signin';
import config from './src/aws-exports';
// Amplify connect
Amplify.configure(config);
// Google app connect
GoogleSignin.configure({
scopes: ['openid', 'email', 'profile'],
webClientId:
'xxxx.apps.googleusercontent.com',
offlineAccess: true,
iosClientId:
'xxxx.apps.googleusercontent.com',
androidClientId:
'xxxx.apps.googleusercontent.com',
});
const App: () => React$Node = () => {
const signInGoogle = () => {
GoogleSignin.hasPlayServices()
.then(() => {
GoogleSignin.signIn()
.then(userInfo => {
console.log('userInfo', userInfo);
Auth.federatedSignIn(
'google',
{
token: userInfo.idToken,
expires_at: 60 * 1000 + new Date().getTime(), // the expiration timestamp
},
userInfo.user,
)
.then(cred => {
// If success, you will get the AWS credentials
console.log('cred', cred);
return Auth.currentAuthenticatedUser();
})
.then(user => {
// If success, the user object you passed in Auth.federatedSignIn
console.log('user after federated login', user);
})
.catch(e => {
console.log('federated login error', e);
});
})
.catch(error => {
console.log(error);
});
})
.catch(error => {
console.log('userInfo error', error);
});
};
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<Button title="Sign in with Google" onPress={() => signInGoogle()} />
</SafeAreaView>
</>
);
};
export default App;
Leave a Reply