Search code examples
amazon-web-servicesauthenticationamazon-cognitoaws-amplifyaws-amplify-cli

Cognito authentication with username or unique email via AWS Amplify


Amplify CLI authentication with Cognito user pools currently has two main modes, signin with username or with email. In the former case email uniqueness as a required user attribute is not being enforced.

Cognito service by itself supports the "Also allow sign in with verified email address" option (AWS Console, User Pool Attributes-section) but it can be set only upon user pool creation (i.e. can not be modified later - checkboxes are disabled). Is it possible to enforce no duplicate emails within the user pool while allowing users to authenticate with username or with email?

To summarize, my use case requires:

  • Verifying/enforcing email attribute uniqueness at the Cognito level when signing up users via Amplify's Auth.SignUp;
  • Keeping username-based login but allowing users to login with their email as well (that is, Auth.SignIn with email or username supplied as the username-argument).

Solution

  • Check out Cognito Lambda Triggers.

    The pre sign-up trigger should meet your use case.

    You can create a custom lambda where you can define the logic of enforcing unique email address. You then register this lambda with Cognito, so it will get called before signup and give you the chance to deny signup if the email already exists.

    To check if a user already exists with the same email, you can use Cognito's ListUsers API with a filter set to email address = signup request's email address. If any results are returned, deny the signup request.