You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWS Amplify实现Google登录认证:federatedSignin返回null?

Hey there! I get it—trying to wire up Google auth with AWS Amplify and make sure user data lands in your Cognito User Pool can feel like navigating a maze, even after reading a bunch of blogs. Let me break this down clearly for you, step by step.

解决AWS Amplify整合Google认证并同步用户信息到Cognito用户池的流程

一、先搞定核心前置配置(这步错了后面全白搭)

First off, make sure your Cognito User Pool is properly connected to Google as an identity provider:

  • Head to the AWS Console, find your Cognito User Pool, go to the Identity providers tab, and add Google.
  • Paste in the Client ID and Client Secret you got from Google’s Developer Console, and set scopes to at least email and profile (these let Google send user data like name and email).
  • Add your app’s callback URL (e.g., http://localhost:3000/ for local dev) to both Google’s OAuth authorized redirects and Cognito’s sign-in/sign-out URLs.

In your frontend project, confirm Amplify is configured with the auto-generated aws-exports.js file (this gets created when you run amplify init and add auth):

import Amplify from 'aws-amplify';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);

二、推荐:用Amplify原生的Google认证(不用手动gapi)

You don’t need to mess with raw gapi calls—Amplify’s Auth module already handles syncing Google user data to Cognito automatically. Here are two easy ways:

1. Use Amplify’s pre-built Authenticator component (simplest option)

This component renders a full login UI with a Google button out of the box, and syncs user data to Cognito instantly:

import { Amplify } from 'aws-amplify';
import { Authenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);

function App() {
  return (
    <Authenticator>
      {({ user }) => (
        <div>
          <h1>Hey, {user.attributes.name}!</h1>
          <p>Your email: {user.attributes.email}</p>
          <img src={user.attributes.picture} alt="Profile pic" />
        </div>
      )}
    </Authenticator>
  );
}

2. Manual OAuth sign-in (for custom buttons)

If you want to build your own login button, call Amplify’s Auth.signInWithOAuth directly:

import { Auth } from 'aws-amplify';

const handleGoogleLogin = async () => {
  try {
    const user = await Auth.signInWithOAuth({
      provider: 'Google',
      // Optional: Override the redirect URL if needed
      // redirectSignIn: 'http://localhost:3000/dashboard'
    });
    // After login, user.attributes has all the synced Google data
    console.log('Cognito user data:', user.attributes);
  } catch (err) {
    console.error('Login failed:', err);
  }
};

// Use this in your button
<button onClick={handleGoogleLogin}>Sign in with Google</button>

三、If you already use raw gapi: Sync data to Cognito manually

If your project already uses gapi for login and you don’t want to rewrite it, use Amplify’s Auth.federatedSignIn to pass Google’s credentials to Cognito—this will create/update the user and sync their data:

Adjust your existing googleSigninCallback like this:

const googleSigninCallback = async (googleUser) => {
  const googleResponse = googleUser.getAuthResponse();
  const profile = googleUser.getBasicProfile();
  
  try {
    // Pass Google's id_token to Amplify to link with Cognito
    const user = await Auth.federatedSignIn(
      'google',
      { token: googleResponse.id_token },
      {
        name: profile.getName(),
        email: profile.getEmail(),
        picture: profile.getImageUrl()
      }
    );
    
    // Success! The user's Google data is now in your Cognito User Pool
    console.log('Synced Cognito user:', user.attributes);
  } catch (err) {
    console.error('Failed to sync with Cognito:', err);
  }
};

四、Verify the data is in Cognito

Head back to the AWS Console, go to your Cognito User Pool, and check the Users and groups tab. Click on the user you just logged in with, and look at the User attributes section—you’ll see email, name, picture, and other Google-synced fields filled in.

Quick troubleshooting tips

  • If data isn’t syncing: Double-check that Google’s OAuth scopes include email and profile.
  • Login errors: Make sure your callback URLs match exactly in both Google’s Developer Console and Cognito.
  • If using raw gapi: Always pass the id_token (not access_token) to federatedSignIn—Cognito uses this to validate and parse user data.

内容的提问来源于stack exchange,提问作者Faizuddin Mohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:05:14