Problem Description:I'm encountering challenges when attempting to add an identity provider (IdP) to an existing user in an AWS Cognito user pool using the OIDC (OpenID Connect) protocol.
Symptoms:Difficulty identifying the appropriate method to link the OIDC provider to an existing user.Uncertainty about which API operations and parameters to use for linking the provider.
Here is my code for pre-signup lambda function in node-js.
const { CognitoIdentityProviderClient, ListUsersCommand, AdminLinkProviderForUserCommand,} = require("@aws-sdk/client-cognito-identity-provider");const cognitoClient = new CognitoIdentityProviderClient({});exports.handler = async (event) => { if (event.triggerSource === "PreSignUp_ExternalProvider") { const { userPoolId, request: { userAttributes }, } = event; const email = userAttributes["email"]; // Check if the email already exists const userList = await cognitoClient.send( new ListUsersCommand({ UserPoolId: userPoolId, Filter: `email = "${email}"`, }) ); if (userList.Users && userList.Users.length > 0) { const [providerName, providerUserId] = event.userName.split("_"); let sourceProviderName; let providerAttributeName; switch (providerName) { case "google": sourceProviderName = "Google"; providerAttributeName = "Cognito_Subject"; break; case "azureadidp": sourceProviderName = "azureadidp"; providerAttributeName = "sub"; break; default: return event; } // Link the provider to the existing user await cognitoClient.send( new AdminLinkProviderForUserCommand({ DestinationUser: { ProviderAttributeValue: userList.Users[0].Username, ProviderName: "Cognito", }, SourceUser: { ProviderAttributeName: providerAttributeName, ProviderAttributeValue: providerUserId, ProviderName: sourceProviderName, }, UserPoolId: userPoolId, }) ); } else { console.log("User not found, skipping link."); } } return event;};
Attempts to Resolve:Initially tried using the AdminLinkProviderForUserCommand operation but encountered issues with identifying the correct parameters.Explored AWS documentation and online resources but struggled to find clear guidance on the OIDC-specific implementation details.Request for Assistance:I'm seeking guidance on the correct approach and specific steps to link an OIDC provider (such as Google or AzureAD) to an existing user in an AWS Cognito user pool. Additionally, I need assistance with identifying the necessary API operations, parameters, and any additional configuration steps required for successful implementation.