Search code examples
regexamazon-web-servicesoauthpasswordsamazon-cognito

AWS Cognito Password Regex - Specific to AWS Cognito


Can someone give me the regex to match a valid AWS Cognito password - with numbers, special characters (their list), lower and upper case letters

The AWS Cognito default length limit is 6 characters and has it's own list of special characters

Note that the AWS Congito password regex is specific to AWS Congnito - not just a general password regex.


Solution

  • Updated Answer - March 2023


    /^(?!\s+)(?!.*\s+$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[$^*.[\]{}()?"!@#%&/\\,><':;|_~`=+\- ])[A-Za-z0-9$^*.[\]{}()?"!@#%&/\\,><':;|_~`=+\- ]{8,256}$/
    

    Explanation

    • / Indicates the start of a regular expression.
    • ^ Beginning. Matches the beginning of the string.
    • (?!\s+) Disallows leading spaces.
    • (?!.*\s+$) Disallows trailing spaces.
    • (?=.*[a-z]) Requires lowercase letters.
    • (?=.*[A-Z]) Requires uppercase letters.
    • (?=.*[0-9]) Requires numbers.
    • (?=.*[\^$*.[\]{}()?"!@#%&/\\,><':;|_~`=+\- ]) Requires at least one special character from the specified set. (The non-leading, non-trailing space character is also treated as a special character.)
    • [A-Za-z0-9^$*.[\]{}()?"!@#%&/\\,><':;|_~`=+\- ]{8,256} Minimum 8 characters from the allowed set, maximum 256 characters.
    • $ End. Matches the end of the string.
    • / Indicates the end of a regular expression.

    The minimum character limit defaults to 8 but can be customised to a value between 6 and 99. The full length of a password however is limited to 256 characters (not 99).

    Interactive Example

    https://regexr.com/79p07

    Documentation

    https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-policies.html

    Inaccuracies in documentation

    Cognito also has a "no leading or trailing spaces" rule in the default password requirements, but there are several docs out there that incorrectly state that "The space character is also treated as a special character". However, the current behaviour is actually "The non-leading, non-trailing space character is also treated as a special character".

    To see the correct default password rules, view a user pool, click on the "Sign-in experience" tab, and click on "Contains at least 1 special character" to bring up a tooltip with the rules.