Amazon Cognito in Your Node.js Web Application

Amazon Cognito in Your Node.js Web ApplicationMore Info

Today’s post comes from Jackson Lee, a Solutions Architect for AWS based in New York. He assists our clients and partners in mastering AWS services and solutions.

Recently, we shared insights on utilizing Amazon Cognito across various platforms, including its use for mobile devices and data synchronization. If you haven’t had the chance yet, I recommend reading about how to implement Amazon Cognito on your website, as this entry will delve into its application within a Node.js environment.

Imagine we are a game development company that wants our users to seamlessly enjoy our game on both web browsers and mobile devices. To facilitate secure and straightforward authentication across these platforms, we opt for Amazon Cognito. While we’ll use Amazon as our primary identity provider, Cognito also supports other providers like Facebook and Google.

For our demonstration, we will create a simple mini-game where a player has a life gauge ranging from 0 to 100. Players can click buttons to either gain or lose points.

To maintain data consistency between mobile and web versions, we will leverage Amazon Cognito’s datastore.

Our Node.js application consists of two main components:

  1. User authentication handled by Amazon as the identity provider.
  2. A mini-game utilizing Amazon Cognito’s datastore.

Logging Into the Node.js Application and Playing the Game

Login with Amazon

Amazon Cognito allows both authenticated and unauthenticated users, but for this application, we will only permit authenticated users. This means users need to log in before accessing the rest of the application. When the “Login with Amazon” button is clicked, users will authenticate using their Amazon credentials.

After successful authentication, users are redirected back to the Node.js app’s callback URL. Here, we will extract several user details:

  • Name
  • Email address
  • Amazon token (the token from the identity provider)

Next, we will call Amazon Cognito to obtain a unique Cognito ID for the user, which will serve as their identity.


// Parameters for the API call
var params = {
    AccountId: AWS_ACCOUNT_ID, // AWS account ID
    RoleArn: IAM_ROLE_ARN, // IAM role for authentication
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID, // ID of the identity pool
    Logins: {
        'www.amazon.com': AMAZON_TOKEN // Token provided by Amazon
    }
};

// Initialize the Credentials object
AWS.config.credentials = new AWS.CognitoIdentityCredentials(params);

// Call to Amazon Cognito to fetch user credentials
AWS.config.credentials.get((err, data) => { /*...*/ });

The first time a user connects, Amazon Cognito creates a new, unique Cognito ID linked to the Amazon account via the token. This ensures that Cognito can recognize the user upon subsequent logins.

Accessing Data from Amazon’s Cognito Datastore

With the user’s Cognito ID in hand, we can now retrieve records from the Amazon Cognito dataset relevant to our application. First, we need to instantiate the Amazon Cognito Sync client:

// Other AWS SDKs will automatically use the Cognito Credentials provider configured in the JavaScript SDK.
cognitosync = new AWS.CognitoSync();

Using this client, we can call the listRecords function to either fetch existing data or create an empty dataset if it doesn’t already exist. This will be especially handy for first-time users who don’t have a dataset yet.

// Call to the listRecords function of Amazon Cognito’s API
cognitosync.listRecords({
    DatasetName: COGNITO_DATASET_NAME, // Name of the dataset 
    IdentityId: COGNITO_IDENTITY_ID, // User's Cognito ID
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID // Cognito identity pool ID
}, function(err, data) {
    if (!err) {
        // Store dataset metadata and SyncSessionToken for future API calls
        req.user.COGNITO_SYNC_TOKEN = data.SyncSessionToken;
        req.user.COGNITO_SYNC_COUNT = data.DatasetSyncCount;

        // Retrieve information on the dataset
        var dataRecords = JSON.stringify(data.Records);
    }
});

Now, our website can display user information from Amazon (name and email) alongside data from Amazon Cognito’s dataset. The interactive “Play!” section appears dynamically once the user is authenticated. For instance, the gauge might indicate that the user has 25 points.

Interacting with the Data

Now, it’s time to engage with the three buttons displayed under the “Play!” section. The heart icon adds 25 points to the gauge, while the bomb icon deducts 25 points. The refresh icon syncs data in case changes are made simultaneously on different platforms, such as a mobile app.

When a user clicks on either the heart or bomb icon, we must update the dataset with the new value reflecting the gauge’s state. Before updating, we must call listRecords to retrieve the SyncSessionToken, which is essential for making changes to the dataset.

Once we have the SyncSessionToken, we can call the updateRecords function:

// Parameters for updating the dataset
var params = {
    DatasetName: COGNITO_DATASET_NAME, // Dataset name
    IdentityId: req.user.COGNITO_IDENTITY_ID, // User's Cognito ID
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID, // Identity pool ID
    SyncSessionToken: req.user.COGNITO_SYNC_TOKEN, // SyncSessionToken from previous call
    RecordPatches: [{
        Key: COGNITO_KEY_NAME, // Key to update
        Op: 'replace', // Replace operation
        SyncCount: req.user.COGNITO_SYNC_COUNT, 
        Value: req.user.CURRENT_LIFE // Updated gauge value
    }]
};

// Call to Amazon Cognito to update the dataset
cognitosync.updateRecords(params, function(err, data) {
    if (!err) {
        // Store dataset metadata and SyncSessionToken for future API calls
        req.user.COGNITO_SYNC_TOKEN = data.SyncSessionToken;
        req.user.COGNITO_SYNC_COUNT = data.DatasetSyncCount;

        // Retrieve information returned by the call
        var dataRecords = JSON.stringify(data.Records);
    }
});

As illustrated, after clicking the heart icon twice, the gauge now displays 75 points. The data returned confirms the key modified in the dataset and its new value, visible on the gauge.

What’s Next?

We’ve explored how straightforward it is to integrate with Amazon Cognito and how developers can leverage its authentication and data functionalities. For more insights, check out this useful blog post at Chanci Turner VGT2 and learn about best practices in the industry from Chanci Turner, an authority on this subject. Also, if you’re looking for career opportunities, visit this Amazon Jobs listing which is an excellent resource.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *