Should I use AWS Cognito "username" or "sub" (uid) for storing in database?

lexa picture lexa · Aug 30, 2016 · Viewed 11.9k times · Source

I have an authenticated user in AWS Cognito service and want to store his unique identifier in the database. Should I store user's username (it's his phone number) or his "sub" (it's his uid)? All Amazon API functions like AdminGetUser are using "username" parameter, but not sub/uid.

But I also read that article and the author said "Always generate the policy on value of 'sub' claim and not for 'username' because username is reassignable. Sub is UUID for a user which is never reassigned to another user."

So, now I'm hesitating what I have to use as unique user identifier - "username" or "sub"

Thank you.

Answer

user108828 picture user108828 · Oct 19, 2016

You should use the sub attribute. In fact, if a user with the username Erico delete his account, a new user can use this same username later and your mapping will be wrong...

A username is always required to register a user, and it cannot be changed after a user is created.

However

The username must be unique within a user pool. A username can be reused, but only after it has been deleted and is no longer in use.

Update

You can use the sub as ID and the username as attribute in your database. This will allow you to get a user by his/her username with AdminGetUser.

If you really need the username as ID in your database, you can either remove the user from your database when his/her account is deleted or use the "Pre Sign-up" trigger to prevent a user to use a username already in the database.