要实现Amplify/Cognito OAuth联合登录(Google)并在同一页中进行重定向,可以按照以下步骤进行操作:
npm install aws-amplify
amplify init
amplify add auth
按照提示选择Cognito服务并设置相关配置。
npm install google-auth-library
import Amplify, { Auth } from 'aws-amplify';
import { GoogleAuth } from 'google-auth-library';
// 初始化Amplify配置
Amplify.configure({
Auth: {
region: 'YOUR_COGNITO_REGION',
userPoolId: 'YOUR_USER_POOL_ID',
userPoolWebClientId: 'YOUR_USER_POOL_CLIENT_ID',
oauth: {
domain: 'YOUR_COGNITO_DOMAIN',
redirectSignIn: 'http://localhost:3000',
redirectSignOut: 'http://localhost:3000',
responseType: 'code',
},
},
});
// 创建Google OAuth客户端
const googleAuth = new GoogleAuth({
clientId: 'YOUR_GOOGLE_CLIENT_ID',
});
// 处理Google OAuth登录回调
const handleGoogleLogin = async () => {
const url = googleAuth.generateAuthUrl({
access_type: 'offline',
scope: 'email',
redirect_uri: 'http://localhost:3000',
});
// 在同一页中进行重定向
window.location.href = url;
};
// 处理Cognito重定向回调
const handleCognitoRedirect = async () => {
if (window.location.search.includes('code=')) {
const code = new URLSearchParams(window.location.search).get('code');
// 使用授权码交换访问令牌
const tokens = await Auth.federatedSignIn(
'google',
{ token: code },
{ customProvider: 'google' }
);
// 处理登录成功逻辑
console.log('登录成功', tokens);
}
};
// 在页面加载时处理重定向回调
window.addEventListener('load', handleCognitoRedirect);
请确保替换代码中的YOUR_COGNITO_REGION、YOUR_USER_POOL_ID、YOUR_USER_POOL_CLIENT_ID和YOUR_COGNITO_DOMAIN为您的Cognito服务配置信息,并将YOUR_GOOGLE_CLIENT_ID替换为您的Google OAuth客户端ID。
以上代码将在加载页面时监听重定向回调,并在Google OAuth登录按钮点击时重定向到Google登录页面。登录成功后,将使用授权码从Cognito交换访问令牌,并将结果打印在控制台中。