根据AWS Cognito的文档,要想使用第三方身份验证提供程序,需要在AWS Cognito中添加相应的“身份提供者”(Identity Provider),包括Google。同时,需要将相应的OAuth 2.0客户端ID和客户机密添加到Google身份提供者设置中。
例如,以下是使用AWS Amplify和React Native创建Google登录的示例代码。
首先,安装必要的依赖项:
npm install aws-amplify @aws-amplify/ui-react react-native-google-signin react-native-linking
接下来,将Google身份提供者添加到AWS Cognito:
import Amplify, { Auth } from 'aws-amplify';
Amplify.configure({
Auth: {
identityPoolId: 'YOUR_IDENTITY_POOL_ID',
region: 'YOUR_REGION',
userPoolId: 'YOUR_USERPOOL_ID',
userPoolWebClientId: 'YOUR_APP_CLIENT_ID',
oauth: {
domain: 'YOUR_AUTH_DOMAIN',
scope: ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin'],
redirectSignIn: 'com.yourapp://callback/',
redirectSignOut: 'com.yourapp://signout/',
responseType: 'code',
options: {
AdvancedSecurityDataCollectionFlag: true
}
},
identityProviders: {
Google: {}
}
}
});
这里的“YOUR_IDENTITY_POOL_ID”、“YOUR_REGION”、“YOUR_USERPOOL_ID”和“YOUR_APP_CLIENT_ID”可以在AWS Cognito控制台中找到。
接下来,使用React Native和Google登录按钮创建UI:
import React from 'react';
import { View, Button } from 'react-native';
import { GoogleSigninButton } from 'react-native-google-signin';
import { Auth } from 'aws-amplify';
import { onSignIn } from './auth';
export default class LoginScreen extends React.Component {
async googleSignIn() {
try {
const user = await GoogleSignin.signIn();
const accessToken = user.accessToken;
const { idToken, email } = user;
const credentials = await Auth.federatedSignIn(
'google',
{ token: idToken, access_token: accessToken },
{ email }
);
onSignIn(credentials);
this.props.navigation.navigate('App');
} catch (error) {
console.log(error);
}
}
render() {
return (
this.googleSignIn()}
disabled={this.state.isSigninInProgress}
/>
);
}
}
这里,“onSignIn”函数是用来将凭据存储在本地的,以便在用户下次打开应用程序时自动登录。另外,为了使应用程序能够正确地处理Google登录后的回调,需要在应用程序的链接中包含一个自定义方案(例如“com.yourapp”)。
最后,确保应用程序的Android清单文件中包含以下代码:
这些都是使Google登录与AWS Cognito的UI一起工作所需的步骤。