Eitan
Eitan

Reputation: 1494

How to retrieve a Cognito user's unique identifier from a bearer token to save user related data in a web api backend

This is crazy, I can't find any documentation from Amazon or other sources describing how to save user related data in my web api backend when integration with AWS Cognito. It seems like a fairly ubiquitous use case.

So for example, let's say I'm creating a backend that includes Exercises that a user can create. The Exercises are isolated to the user so I need a userId foreign key column on the Exercise table (I'm using and RDBMS called SQL Server but I'd still have the same question for a NOSQL database). The frontend is using React, Amplify, and AppSync to connect to the backend web API lambda (C# .NET Core).

I thought, I would call Auth.signIn, store the bearer token and pass it in the Authorization header, which AppSync would pass to the API. In the API, I need to get the unique identifier to retrieve or save exercises (or any other user related data for that matter).

What is the best practice once I reach the API side and I have a bearer token? Can/Should I use it to retrieve a user object from Cognito and if so, what unique property can I use as an ID? Should I create my own custom attribute on the user pool called User Id and save a guid that is generated during sign up? Is there an article or source I can read how to do this? It seems like all the tutorials are how to authenticate and authorize resources like controller actions or AWS resources but not how to retrieve the unique identifier for a user once the user is authenticated and authorized. Most the entities in my application are connected to a user so fairly important.

I'm also using federated sign in with Google and Facebook.

Upvotes: 1

Views: 456

Answers (1)

Jeremy Thompson
Jeremy Thompson

Reputation: 65554

You pass the token in the Authorization header and typically you post the encrypted UserId/info to the Gateway API.

You can actually generate the calling code for GatewayAPI & Lambda. This will show you how to do it. Goto the GatewayAPI Staging (deploy to staging if you haven't yet), select the SDK tab, select your language and generate. These are where all the examples are:

Image of AWS Gateway API calling code generator

Upvotes: 1

Related Questions