Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

From AWS Cognito to DynamoDB Using Triggers

DZone's Guide to

From AWS Cognito to DynamoDB Using Triggers

One of the features of AWS Cognito that I find most interesting is the use of Triggers to extend the default flows. We'll discuss these here.

· Security Zone ·
Free Resource

Protect your applications against today's increasingly sophisticated threat landscape.

In previous articles, we looked at how to use AWS Cognito, an Identity as a Service provider. One of the features of AWS Cognito that I find most interesting is the use of Triggers to extend the default flows. These triggers are serverless functions using another Amazon service, AWS Lambda.

Triggers on AWS Cognito

Event triggers allow us to customize actions to send a personalized message, before or after authentication or after confirmation. The complete information on the triggers and their data model is available in the documentation. In our example, we are going to use the Post Confirmation Trigger.

Table in DynamoDB - Part I

In this example, we will see how an entry in DynamoDB can be generated after the user confirms the account. The table will save the information of the registered user. The creation of the table and the features of DynamoDB and NoSQL is not part of this article but it is super simple. Like the rest of the AWS services, it can be done directly from the console.

Post Confirmation Trigger - Part I

The first thing is to create a function in AWS Lambda. It can be created using different programming languages. In this example, we will use Node.js since it allows us to use the online editor.

After creating the function, it appears in the drop-down options, you just need to select it and that's it. When Cognito invokes the function, it does so with a data schema of the given events. This is important in order to define the test case.

Security Policy

Now we must implement the logic of the function, but, first, we must configure the security policy that will allow the lambda function to access the table in DynamoDB. Otherwise, the function will generate an error when we try to save the record in the table. Security policies are created and managed from the Amazon Web Services IAM service.

Below is the JSON representation of the security policy.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "dynamodb:PutItem",
            "Resource": "arn:aws:dynamodb:*:*:table/Usuarios"
        }
    ]
}

Post Confirmation Trigger - Part II

Now, we can write the function that will process the event. The function has to include the necessary libraries to access DynamoDB.

The code is simple, we have to assign the values of the event to the structure that we are going to use to insert in DynamoDB and finally invoke the function to perform the insert. Something that happened to me as my first time using DynamoDB, the strings to insert cannot be empty. If we want the field to be in the item even if it is empty, it is necessary to insert it as null.

const 
    aws = require('aws-sdk'),
    uuidv4 = require('uuid/v4');

const ddb = new aws.DynamoDB({apiVersion: '2012-10-08'});

exports.handler = function(event, context, callback) {
    var d = new Date();
    var uuidUser = uuidv4();

    var paramsUsuarios = {
        TableName: 'Usuarios',
        Item: {
            "UsuarioID": { "S": event.userName },
            "UsuarioUUID": { "S": uuidUser },
            "Nombre": { "S": event.request.userAttributes.given_name },
            "Apellido": { "S": event.request.userAttributes.family_name },
            "Email": { "S": event.request.userAttributes.email },
            "Creado": { "S": d.toISOString()},
            "Modificado": { "S": d.toISOString()}
        }
    };

    ddb.putItem(paramsUsuarios, function(err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Exito", data);
      }
    });  
};

Test Case

In order to test the function, it is necessary that we configure a test case that is equal to the data that the function will receive from Cognito when it is invoked. The documentation shows the parameters for each of the Cognito triggers. In our case, the test case looks like this:

{
  "version": 1,
  "triggerSource": "PostConfirmation_ConfirmSignUp",
  "region": "us-east-1",
  "userPoolId": "us-east-1_EXMumaRTw",
  "userName": "lopezlucas",
  "callerContext": {
    "awsSdk": "aws-sdk-java-console",
    "clientId": "20tb0plr6q7i73q1katr00kuo7"
  },
  "request": {
    "userAttributes": {
      "sub": "0dsf0d44-45d2-8d10-811n-02452c6a643d",
      "cognito:user_status": "CONFIRMED",
      "email_verified": "true",
      "cognito:email_alias": "email@email.com",
      "given_name": "Lucas",
      "family_name": "Lopez",
      "email": "email@email.com"
    }
  },
  "response": {}
}

After creating the test case, we can test the function.

End-to-End Execution

Using the app that we assembled in the previous article when registering and confirming the user, AWS Cognito will execute the function before returning to the app. If we check the table in DynamoDB we will find the data that was inserted from the function thanks to the information propagated to the trigger.

Table in DynamoDB - Part II

As an extra, let's see what we have to do if instead of inserting into a single table we want to affect two tables. First, we have to create the new table and modify the security policy.

Post Confirmation Trigger - Part III

Then, it is only necessary to modify the lambda function but there is a caveat. When having to insert in two tables, it is necessary to consider that the calls to functions of DynamoDB are asynchronous and what is necessary to wait for that they finish both. The way to achieve this in Node.js is using Promises.

const 
    aws = require('aws-sdk'),
    uuidv4 = require('uuid/v4');
const ddb = new aws.DynamoDB({apiVersion: '2012-10-08'});

exports.handler = function(event, context, callback) {
    var d = new Date();
    var uuidUser = uuidv4();

    var paramsUsuarios = {
        TableName: 'Usuarios',
        Item: {
            "UsuarioID": { "S": event.userName },
            "UsuarioUUID": { "S": uuidUser },
            "Nombre": { "S": event.request.userAttributes.given_name },
            "Apellido": { "S": event.request.userAttributes.family_name },
            "Email": { "S": event.request.userAttributes.email },
            "Creado": { "S": d.toISOString()},
            "Modificado": { "S": d.toISOString()}
        }
    };
    var paramsIDs = {
        TableName: 'Usuarios2',
        Item: {
            "UsuarioUUID": { "S": uuidUser },
            "NombreCompleto": { "S": event.request.userAttributes.given_name + " " + event.request.userAttributes.family_name },
            "IDTipo": { NULL: true},
            "IDNumeror": { NULL: true},
            "CreateDateTime": { "S": d.toISOString()},
            "UpdateDateTime": { "S": d.toISOString()}
        }
    };    
    var usuariosPromise = ddb.putItem(paramsUsuarios).promise()
        .then( function(data) { console.log('Exito Usuarios');return true;}
        ).catch( function(err) { console.log("Error Usuarios: "+err); return false; });

    var usuarios2Promise = ddb.putItem(paramsIDs).promise()
        .then( function(data) { console.log('Exito Usuarios2');return true;}
        ).catch( function(err) { console.log("Error Usuarios2: "+err);return false;});        

    Promise.all([usuariosPromise, usuarios2Promise])
        .then(function(values) { 
                if (values[0] && values[1]) context.succeed(event);
                else context.fail("error");
            }
        ).catch(
            function(err) {  context.fail(err); }
        );
};

To be honest, the first time I wrote a similar function, I did not take into account this situation and I got confused thinking that the problem was in another part of the function.

Final Words

The triggers in AWS Cognito are an excellent feature that can be used to extend the management flows of users and identities beyond what AWS Cognito offers by default. The only consideration is that the Lambda functions have a separate cost to Cognito, although the free tier includes a free amount of executions of Lambda functions.

All views expressed are my own and do not represent opinions of any entity whatsoever with which I have been, am now, or will be affiliated.

Rapidly detect security vulnerabilities in your web, mobile and desktop applications with IBM Application Security on Cloud. Register Now

Topics:
identity as a service ,security ,authentication ,web application security ,aws lambda

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}