Amazon Cognito: managing mobile account data

Amazon Cognito allows secure authentication in a world where mobile apps are regularly being accessed by individuals using multiple smart devices

Amazon Cognito is an Amazon Web Service that offers mobile identity management and data synchronization across devices. We’ll first take some time to make sure we’re clear about exactly what Cognito does, then we’ll dive right in with a simple Java application.
First though, just what are data synchronization and identity management?
With the explosion in mobile applications being accessed by individuals using multiple smart devices, keeping accounts consistent and updated has been a challenge. The trick is to effectively manage user data like settings, preferences, and application state. Launching a simple app can now require the infrastructure to managing details like data sync, network state and storage.
Amazon Cognito addresses these challenges and allows developers to concentrate more on application development.
In the days before Amazon Cognito, Identity Management naturally required authentication before gaining application access to any AWS resources. An application would need to pass in a valid AWS account ID and its credentials (both Secret Key and Access Key). Securing AWS credentials dynamically was always a concern: One cannot hard code the credentials within applications, as that breaks best practices. Storing credentials on an encrypted file system doesn’t sound like a perfect solution either.
Amazon Cognito offers a reliable and secure way to access AWS resources without having to produce credentials upfront (although AWS account details are still required). The system gives your users unique identifiers and ensures that they remain consistent across devices.
How does this work?Amazon Cognito has users authenticate via public login Providers (like Google and Facebook). With Cognito now in the driver’s seat, your app’s permissions are carefully respected while it gains access to precisely the AWS resources it needs. Your users will enjoy their smooth experience, while you can remain confident that your credentials aren’t dangerously exposed.
This illustrates the authentication flow when an app tries to access AWS services via public login providers:
Amazon Cognito - public providers
Developer authentication system
For various reasons, mobile app users sometimes choose not to use the account of a public login provider, but rather prefer the authentication mechanism provided by the application itself. Amazon Cognito is flexible enough to allow application developers their own authentication systems.
This diagram shows the authentication workflow for an app trying to access AWS services via a developer authentication system:
Amazon Cognito - Developer authentication system

Getting Started with Amazon Cognito

Now let’s see how the authentication actually works. We’ll try writing some application code to get a feel for making API calls like GetId, GetOpenIdToken, AssumeRoleWithWebIdentity, and most importantly, the AWS Security Token Service (STS).
In this example, we’ll use Amazon Cognito with an application that doesn’t have required AWS credentials, but can still access the AWS S3 service to upload a file from local file system:
1. Create an identity pool in the Amazon Cognito console. The pool will look like the image below. The identity pool will let you to create a new IAM role (or use the existing one) for your app user. Once you have an IAM role, it will give you access to the necessary AWS resources using temporary credentials. We’ll see how identity pool details will be used in application code in just a moment.
Amazon Cognito - IAM
As you can see, by checking “Enable access to unauthenticated identities”, we are allowing unauthorized users. But because we are doing so, we have to be very careful assigning privileges to this user. This can be controlled by attaching an appropriate policy for the corresponding role.
For our example, the policy for the Cognito_testcognitoidentityUnauth_Role should be:
Amazon Cognito - Role
2. Make a note of the ARN, as we will use it while writing the application. Click “Show ARN” to get the details, as below:
Amazon Cognito - ARN 3. Now, if you have Eclipse running, create a simple java project with a class called TestAWSCognitoIdentityProvider, using this content for the class:

import java.io.File;
import java.util.Date;
import com.amazonaws.auth.AWSSessionCredentials;
import com.amazonaws.auth.AnonymousAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentity;
import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.services.cognitoidentity.model.GetIdRequest;
import com.amazonaws.services.cognitoidentity.model.GetIdResult;
import com.amazonaws.services.cognitoidentity.model.GetOpenIdTokenRequest;
import com.amazonaws.services.cognitoidentity.model.GetOpenIdTokenResult;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient;
import com.amazonaws.services.securitytoken.model.AssumeRoleWithWebIdentityRequest;
import com.amazonaws.services.securitytoken.model.AssumeRoleWithWebIdentityResult;
public class TestAWSCognitoIdentityProvider {
  /**
  As far a
  * @param args
  */
  public static void main(String[] args) {
    // initialize the Cognito identity client with a set
    // of anonymous AWS credentials
    AmazonCognitoIdentity identityClient = new AmazonCognitoIdentityClient(new AnonymousAWSCredentials());
    identityClient.setEndpoint(“<<set endpoint for AWS cognito>>”);
    GetIdRequest idRequest = new GetIdRequest();
    idRequest.setAccountId(“<<Here you should give your aws accound number>>“);
    idRequest.setIdentityPoolId(“<<Provide endpoint for identitypool>>“);
    GetIdResult idResp = identityClient.getId(idRequest);
    String identityId = idResp.getIdentityId();
    GetOpenIdTokenRequest tokenRequest = new GetOpenIdTokenRequest();
    tokenRequest.setIdentityId(identityId);
    GetOpenIdTokenResult tokenResp = identityClient.getOpenIdToken(tokenRequest);
    String openIdToken = tokenResp.getToken();
    AWSSecurityTokenService stsClient = new AWSSecurityTokenServiceClient(new AnonymousAWSCredentials());
    AssumeRoleWithWebIdentityRequest stsReq = new AssumeRoleWithWebIdentityRequest();
    stsReq.setRoleArn(“<<Provde the ARN that was noted down in step 2>>“);
    stsReq.setWebIdentityToken(openIdToken);
    stsReq.setRoleSessionName(“AppTestSession”);
    AssumeRoleWithWebIdentityResult stsResp = stsClient.assumeRoleWithWebIdentity(stsReq);
    Credentials stsCredentials = stsResp.getCredentials();
    AWSSessionCredentials sessionCredentials = new BasicSessionCredentials(
      stsCredentials.getAccessKeyId(),
      stsCredentials.getSecretAccessKey(),
      stsCredentials.getSessionToken()
    );
    Date sessionCredentialsExpiration = stsCredentials.getExpiration();
    System.out.println(sessionCredentials.getAWSAccessKeyId());
    String bucketName = “<<Existing bucket name>>”;
    String keyName = “cognitokey”;
    String uploadFileName = “<<File name with path>>”;
    AmazonS3 s3client = new AmazonS3Client(sessionCredentials);
    s3client.setEndpoint(“<<Provide S3 endpoint>>”);
    File file = new File(uploadFileName);
    s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
  }
}

Now let’s try to understand the code. Once you’ve created the identity pool, you need to call the GetId API, providing your AWS account and identity pool details in order to retrieve a unique identifier (also known as a Cognito ID) for your end user.
Amazon Cognito - ID
Now, use the Cognito ID to get an OpenID token. By exchanging your OpenID token with STS (Security token service), you can get temporary, limited-privilege AWS credentials.
Amazon Cognito
AssumeRolewithWebIdentity returns a set of temporary security credentials for users who have been authenticated in a mobile or web application through an OpenID Connect-compatible web identity provider. Besides AssumeRolewithWebIdentity, STS supports other actions. This explains how we used the AWS S3 client with temporary credentials to upload files, instead of having to present a user’s permanent secret key and access key.
Note: To avoid any compilation/runtime errors, make sure you have these jars available in the build path. Or if you are using Maven, make sure you’ve taken care of all dependencies.
Amazon Cognito - Java
4. Once you are all set, you can run this Java program and then verify in S3 whether the file was uploaded or not.

Summary: Amazon Cognito facts

  • Amazon Cognito can be used with Amazon, Facebook, Twitter, Digits, Google, and any other OpenID Connect-compatible identity provider.
  • Amazon Cognito supports unauthenticated guest users (i.e., users who do not authenticate with your own identity system or with one of the supported Identity Providers).
  • Cognito events can be integrated with Amazon Lambda.
  • Data is encrypted at rest in the Amazon Cognito sync store, and all identity data is transmitted over HTTPS.
  • Charges for Amazon Cognito are based on the total amount of app data stored in the Amazon Cognito sync store and the number of sync operations performed. With the AWS Free Tier, you receive 10GB of sync store and 1,000,000 sync operations per month for up to 12 months. After that, it will cost $0.15 per GB of sync store per month and $0.15 for each 10,000 sync operations.
  • AWS Cognito is currently available in the US East (N. Virginia), EU (Ireland), and Asia Pacific (Tokyo) regions.
  • AWS Cognito streams allow streaming user identity data from AWS Cognito to Amazon Kinesis.

Please add your experiences or thoughts to the comments below.

Written by

Working as a cloud professional for last 6 years in various organizations, I have experience in three of the most popular cloud platforms, AWS IaaS, Microsoft Azure and Pivotal Cloud Foundry PaaS platform.Having around 10 years of IT experience in various roles and I take great interest in learning and sharing my knowledge on newer technologies. Wore many hats as developer, lead, architect in cloud technologies implementation. During Leisure time I enjoy good soothing music, playing TT and sweating out in Gym. I believe sharing knowledge is my way to make this world a better place.

Related Posts

— September 18, 2018

How to Optimize Cloud Costs with Spot Instances: New on Cloud Academy

One of the main promises of cloud computing is access to nearly endless capacity. However, it doesn’t come cheap. With the introduction of Spot Instances for Amazon Web Services’ Elastic Compute Cloud (AWS EC2) in 2009, spot instances have been a way for major cloud providers to sell sp...

Read more
  • AWS
  • Azure
  • Google Cloud
— August 23, 2018

What are the Benefits of Machine Learning in the Cloud?

A Comparison of Machine Learning Services on AWS, Azure, and Google CloudArtificial intelligence and machine learning are steadily making their way into enterprise applications in areas such as customer support, fraud detection, and business intelligence. There is every reason to beli...

Read more
  • AWS
  • Azure
  • Google Cloud
  • Machine Learning
— August 17, 2018

How to Use AWS CLI

The AWS Command Line Interface (CLI) is for managing your AWS services from a terminal session on your own client, allowing you to control and configure multiple AWS services.So you’ve been using AWS for awhile and finally feel comfortable clicking your way through all the services....

Read more
  • AWS
Albert Qian
— August 9, 2018

AWS Summit Chicago: New AWS Features Announced

Thousands of cloud practitioners descended on Chicago’s McCormick Place West last week to hear the latest updates around Amazon Web Services (AWS). While a typical hot and humid summer made its presence known outside, attendees inside basked in the comfort of air conditioning to hone th...

Read more
  • AWS
  • AWS Summits
— August 8, 2018

From Monolith to Serverless – The Evolving Cloudscape of Compute

Containers can help fragment monoliths into logical, easier to use workloads. The AWS Summit New York was held on July 17 and Cloud Academy sponsored my trip to the event. As someone who covers enterprise cloud technologies and services, the recent Amazon Web Services event was an insig...

Read more
  • AWS
  • AWS Summits
  • Containers
  • DevOps
  • serverless
— July 11, 2018

AWS Certification Practice Exam: What to Expect from Test Questions

If you’re building applications on the AWS cloud or looking to get started in cloud computing, certification is a way to build deep knowledge in key services unique to the AWS platform. AWS currently offers nine certifications that cover the major cloud roles including Solutions Archite...

Read more
  • AWS
— June 26, 2018

Disadvantages of Cloud Computing

If you want to deliver digital services of any kind, you’ll need to compute resources including CPU, memory, storage, and network connectivity. Which resources you choose for your delivery, cloud-based or local, is up to you. But you’ll definitely want to do your homework first.Cloud ...

Read more
  • AWS
  • Azure
  • Cloud Computing
  • Google Cloud
— March 13, 2018

Choosing the Right AWS Certification for You and Your Team

As companies increasingly shift workloads to the public cloud, cloud computing has moved from a nice-to-have to a core competency in the enterprise. This shift requires a new set of skills to design, deploy, and manage applications in the cloud.As the market leader and most mature pro...

Read more
  • AWS
  • AWS certifications
— March 7, 2018

How to Encrypt an EBS Volume

Keeping data and applications safe in the cloud is one the most visible challenges facing cloud teams in 2018. Cloud storage services where data resides are frequently a target for hackers, not because the services are inherently weak, but because they are often improperly configured....

Read more
  • AWS
  • encryption
— February 28, 2018

How to Develop Machine Learning Models in TensorFlow

Predictive analytics and automation—through AI and machine learning—are increasingly being integrated into enterprise applications to support decision making and address critical issues such as security and business intelligence. Public cloud platforms like AWS offer dedicated services ...

Read more
  • Amazon Machine Learning
  • AWS
  • AWS Labs
— February 15, 2018

Is Multi-Cloud a Solution for High Availability?

With the average cost of downtime estimated at $8,850 per minute, businesses can’t afford to risk system failure. Full access to services and data anytime, anywhere is one of the main benefits of cloud computing.By design, many of the core services with the public cloud and its underl...

Read more
  • AWS
  • Azure
  • Cloud Adoption
  • Google Cloud
— February 13, 2018

Cloud Academy Sketches: Encryption in S3

Some of 2017’s largest data breaches involved unprotected Amazon Simple Storage (S3) buckets that left millions of customer data records exposed to the public. The problem wasn’t the technology, but administrators who improperly configured the security settings.For cloud teams in char...

Read more
  • AWS