Skip to content

Integration between Google sign in and Amazon Cognito

0

I have an issue in my react native application in the Continue with google flow i.e. Federated identity provide sign in, What I need to is if the user in not present in my Cognito user pool , This user shall be signed up in my user pool. If not, User shall be authenticated using its Gmail account.

What I have done so far Is used the following libraries

@react-native-google-sign-in/google-signin and amazon-cognito-identity-js and aws-sdk

I have created a webClientID , Android ClientID, IOSClientID and Configured OAuth Consent Screen and all the other setup needed from google cloud platform. I have enabled Social Providers and attribute mapping between google and Cognito I indeed get the ID token from google , but i get the following error

Error signing up user: [NotAuthorizedException: Client <client_Id> is configured with secret but SECRET_HASH was not received] which is related to missing client secret hash in the authentication request to Cognito after getting the Id token from google , and after investigation it seems that i need to create another App Client with client secret generation disabled in order to bypass this error

export const signInWithGoogle = async () => {
  try {
    await GoogleSignin.hasPlayServices();
    const userInfo = await GoogleSignin.signIn() as any;
    console.log("Google Sign-In Response for user-info:", userInfo);
    const tokens = await GoogleSignin.getTokens();
    console.log("Token :", tokens);
    if (!tokens.idToken) {
      throw new Error("Failed to retrieve Google ID token");
    }

    // ✅ Correct way to access email
    const email = userInfo?.data.user?.email || null;
    console.log("email :", email);
    if (!email) {
      throw new Error("Email not provided by Google Sign-In.");
    }

    console.log("✅ Extracted Email:", email);

    const userExists = await checkIfUserExists(email);

    if (userExists) {
      console.log("User exists, signing in...");
      await signInUser(email);
    } else {
      console.log("User does not exist, signing up...");
      await signUpUser(email);
    }

    await authenticateWithCognitoFederation(tokens.idToken);

    console.log("✅ Authentication successful! Redirecting to Home Page...");
    return tokens.idToken;

  } catch (error) {
    console.error("Google Sign-In Error:", error);
    return null;
  }
};

const authenticateWithCognitoFederation = async (idToken: string) => {

  const credentials = new AWS.CognitoIdentityCredentials(
    {

      IdentityPoolId: IDENTITY_POOL_ID,
      Logins: { "accounts.google.com": idToken },
    },
    { region: "<region>", }
  );

  AWS.config.credentials = credentials;

  await credentials.getPromise();
  console.log("✅ AWS Credentials obtained:", credentials);
};

const signUpUser = async (email: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    const attributes = [new CognitoUserAttribute({ Name: "email", Value: email })];

    userPool.signUp(email, "DUMMY_PASSWORD_123!", attributes, [], (err, result) => {
      if (err) {
        console.error("❌ Error signing up user:", err);
        reject(err);
      } else {
        console.log("✅ User signed up successfully:", result);
        resolve();
      }
    });
  });
};



if fail at signUpUser 
❌ Error signing up user: [NotAuthorizedException: Client <Client_ID> is configured with secret but SECRET_HASH was not received]

So my questions are :

1- Do I have to create a new App Client with no Client Secret enabled In order to bypass the above error?

2- Should I use Identity Pool Instead of Cognito User pool to accomplish the Social Providers Authentication ?

3- Should this be done using the mentioned libraries or Amplify is needed to accomplish the Social Providers Authentication ?

asked 2 years ago492 views

1 Answer
1

To address your issues with Google sign-in and Amazon Cognito integration in your React Native application, I can provide some guidance on your questions:

  1. Yes, creating a new App Client with the client secret generation disabled is a valid approach to bypass the "NotAuthorizedException" error you're encountering. When you create an App Client without a client secret, you won't need to provide the SECRET_HASH in your authentication requests. This can simplify the process, especially for mobile applications where securely storing and managing a client secret can be challenging.

  2. For social provider authentication, you can use both Cognito User Pools and Identity Pools, but they serve different purposes. Cognito User Pools is primarily for user management and authentication, while Identity Pools is for providing temporary AWS credentials to access other AWS services. In your case, since you want to manage user sign-up and sign-in, using a Cognito User Pool is appropriate. You're already on the right track with this approach.

  3. While you can accomplish social provider authentication using the libraries you've mentioned (@react-native-google-sign-in/google-signin, amazon-cognito-identity-js, and aws-sdk), using AWS Amplify can significantly simplify the process. Amplify provides a higher-level abstraction and handles many of the complexities of federation and token management for you. It can make your implementation more straightforward and less error-prone.

However, if you prefer to continue with your current setup, you'll need to ensure you're correctly handling the Google ID token and using it to authenticate with Cognito. After obtaining the Google ID token, you should use it to get Cognito tokens rather than trying to sign up or sign in the user manually.

To improve your current implementation:

  1. Remove the manual sign-up and sign-in logic (signUpUser and signInUser functions).
  2. After getting the Google ID token, use it directly with Cognito to authenticate the user.
  3. Configure your Cognito User Pool to automatically create user profiles for federated users if they don't exist.

This approach will let Cognito handle the user creation and authentication process based on the Google ID token, simplifying your code and reducing potential errors.
Sources
Setting up Google as an identity pool IdP - Amazon Cognito
Does Cognito provide the Id token that is returned by Google ? | AWS re:Post
User pool sign-in with third party identity providers - Amazon Cognito

answered 2 years ago

EXPERT

reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.