Poweranimal
Poweranimal

Reputation: 1699

Store data to DynamoDB with the Cognito userId

I setup my iOS app with the AWS Mobile Hub. The services I'm using are AWS Cognito and AWS DynamoDB.

I created on AWS DynamoDB a private table that has by default the partition key userId. As far as I can tell, AWS DynamoDB only allows the userId to be the identityId from e.g. AWSIdentityManager.

I'm able to successfully establish an user session via AWSCognitoIdentityUserPool.default().currentUser()?.getSession().

I read/write to AWS DynamoDB with the identityId, that I get through AWSIdentityManager.default().identityId, as userId.

However, the identityId stays always the same on the device, even if I have established an user session.

How can I get an identityId from AWSIdentityManager that is specific for an AWS Cognito user?

Upvotes: 2

Views: 1517

Answers (1)

Jacob Lange
Jacob Lange

Reputation: 1369

EDIT:

IdentityId's are unique per cognito user as we discovered together in the comment thread but they are cached on the device and need to be cleared on log out. Clear via swift sdk with:

AWSCognitoIdentityProvider.Clear()

Below is my original answer recommending to use the username or an alias which is also unique per cognito user but it should only be used as reference for the comment discussion. Use IdentityId's as dyanmodb primary keys instead.

END-EDIT:

I would recommend using the username as the partition key in your dynamodb table.

You can get the username from the AWSCognitoIdentityUser object by

if let username = AWSCognitoIdentityUserPool.default().currentUser()?.username {
   // do stuff with username
}

You could also configure the user pool to use custom username alias to allow users to sign in via email and/or phone number. In this scenario, email and/or phone number would also be unique and then if you prefer to, you may use either of those as the unique partition key in your dynamodb table instead. Here's an overview of aliases in cognito.

Upvotes: 3

Related Questions