28

Im building a serverless backend using AWS Cognito for user administration.

Cognito uses both cognitoId and sub to identify a user.

This project from the official awslabs uses the cognitoId as primary key in the database tables to link data to a user object, but the documentation about sub clearly states:

sub: the UUID of the authenticated user. This is not the same as username.

Question: What should I use as primary key, cognitoID or sub?

Vingtoft
  • 13,368
  • 23
  • 86
  • 135

2 Answers2

31

The naming can get confusing, I'll try to clarify.

There are typically two pools under the umbrella of Amazon Cognito:

  • User Pool
  • Identity Pool (Federated Identities)

The "sub" that you are referring to is typically expressed in IAM Policies as

${cognito-identity.amazonaws.com:sub}

and will resolve to the value found in (in the javascript sdk)

AWS.config.credentials.identityId

which will look something like

us-east-1:########-####-####-####-############

It will only exist on the credentials once the credentials have been refreshed.

So to answer you question, the sub.

bleuf1shi
  • 830
  • 7
  • 12
  • 1
    Do federated identities have subs? I'm currently using Facebook as an authentication provider and getting the cognito sub is coming back null, but I have an IdentityId through this method. Using the user pool however I am able to get a sub. – MattyK14 Aug 09 '17 at 13:31
  • 3
    @MattyK14 , as far as I'm aware, No. Subs are like the User ID in the User Pool. Once the pool of user's enters the world of Federated Identities, then users are mapped to identities (many -> one) – bleuf1shi Aug 10 '17 at 21:58
  • Yeah, that was kinda what I derived from my debugging process. Thanks! – MattyK14 Aug 11 '17 at 17:02
  • So if you are both facebook and email via cognito, what should you use as the user's unique identifier? – honkskillet Apr 23 '18 at 13:22
  • 1
    @honkskillet since logins are auto-magically joined onto the same federated identity. The Sub. – bleuf1shi Apr 29 '18 at 19:24
15
  • sub(subject) is globally unique and hence is unique for user pool as well.
  • Unlike username, which can be reassigned to another user in user pool, sub is never reassigned.

Source

Premraj
  • 72,055
  • 26
  • 237
  • 180