- Newest
- Most votes
- Most comments
Hi Thomas,
The issue you're encountering is common when working with Cognito and multiple sign-in methods. Unfortunately, Cognito doesn’t natively merge accounts when a user signs up with the same email via different providers. However, you can work around this using a Pre-Signup Lambda trigger instead of Post-Confirmation.
Here’s a high-level approach:
-
Pre-Signup Trigger: Create a Lambda function to check if the email exists in the User Pool before allowing the new signup. If it exists, link the social provider to the existing account.
-
Link Social Provider: In the Lambda, use the
AdminLinkProviderForUser
API to link the new social login to the existing Cognito user.
Here’s a rough idea:
import { CognitoIdentityProviderClient, AdminLinkProviderForUserCommand, ListUsersCommand, } from "@aws-sdk/client-cognito-identity-provider"; const client = new CognitoIdentityProviderClient({}); export const handler: PreSignUpTriggerHandler = async (event) => { const { userPoolId, request } = event; const email = request.userAttributes["email"]; const listUsersCommand = new ListUsersCommand({ UserPoolId: userPoolId, Filter: `email = "${email}"`, }); const response = await client.send(listUsersCommand); if (response.Users?.length > 0) { const existingUser = response.Users[0]; const linkCommand = new AdminLinkProviderForUserCommand({ UserPoolId: userPoolId, DestinationUser: { ProviderName: "Cognito", ProviderAttributeValue: existingUser.Username, }, SourceUser: { ProviderName: event.userName.split("_")[0], // e.g., "Google" ProviderAttributeName: "Cognito_Subject", ProviderAttributeValue: event.userName.split("_")[1], }, }); await client.send(linkCommand); throw new Error("User linked to existing account."); } return event; };
- Modify Resource Configuration: Ensure your Cognito User Pool is set to prevent duplicate email sign-ups by adjusting the settings under "Attributes" to enforce email uniqueness.
This setup should help you merge the accounts under a single user when signing up via different providers. Let me know if you need further assistance!
Relevant content
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 5 months ago
- AWS OFFICIALUpdated 8 months ago
- AWS OFFICIALUpdated 2 years ago
Hi Vitor, thank you for your response and idea! I've actually tried a Pre-Signup Trigger, but I've read somewhere that the social provider sign-in doesn't trigger it. It seemed to be wrong... I tried out your solution and there are two issues: