Background
Many time when you are creating application be it mobile or web you have to provide an authentication mechanism for users to sign in before they can use your apps or websites features. AWS Cognito service does the same thing.
- Amazon Cognito makes it easy for you to have users sign up and sign in to your apps, federate identities from social identity providers, secure access to AWS resources and synchronize data across multiple devices, platforms, and applications.
You can do 3 things using this service -
- With Cognito Your User Pools, you can easily and securely add sign-up and sign-in functionality to your mobile and web apps with a fully-managed service that scales to support hundreds of millions of users.
- With Cognito Federated Identities, your users can sign-in through social identity providers such as Facebook and Twitter, or through your own identity solution, and you can control access to AWS resources from your app.
- With Cognito Sync, your app can save user data, such as preferences and game state, and sync that data to make your users' experiences consistent across their devices and when they are disconnected.
NOTE: AWS Cognito is a region-specific service so you have to select a region and make sure this service is available in that region. For this post, I am going to use us-east-1(N.Virginia).
Also in this post, I am going to show how we can create a federated identity pool which can be used to authenticate and access AWS resources. Though I am going to limit this post to setting-up the identity pool and corresponding AWS changes we will see how we can use this to upload sample files to Amazon S3 bucket.
How to setup Cognito Identity Pool for unauthenticated or authenticated access to AWS resources
- Now click on "Manage Federated Identities"
- Provide a name for your identity pool. Eg. athakur_test
- If you want unauthenticated users to use this pool for authenticating and accessing AWS resources select "". I am going to select this since finally, I want to use this pool to upload files to S3.
NOTE: Amazon Cognito can support unauthenticated identities by providing a unique identifier and AWS credentials for users who do not authenticate with an identity provider. If your application allows customers to use the application without logging in, you can enable access to unauthenticated identities.
- If you want to provide access to authenticated users only then use one of the Authentication providers like Facebook, Amazon, Google etc
- Click on "create pool".
- Next screen you should see the roles that AWS will create for you. You can select "View details" to see the role details.
- Finally, click "Allow"
NOTE1: Assigning a role to your application end users helps you restrict access to your AWS resources. Amazon Cognito integrates with Identity and Access Management (IAM) and lets you select specific roles for both your authenticated and unauthenticated identities.
NOTE2: By default, Amazon Cognito creates a new role with limited permissions - end users only have access to Cognito Sync and Mobile Analytics. You can modify the roles if your application needs access to other AWS resources, such as S3 or DynamoDB.
You can see click on video details to see this default policy document -
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "mobileanalytics:PutEvents", "cognito-sync:*" ], "Resource": [ "*" ] } ] }
We will see how to attach additional permissions to this role later.
As you can see 2 roles are created - one for the authenticated user and other for the unauthenticated user -
- Cognito_athakur_testAuth_Role
- Cognito_athakur_testUnauth_Role
On the next page, you should see some sample code - one for getting credentials and other for Cognito sync -
Get AWS credentials :
// Initialize the Amazon Cognito credentials provider CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider( getApplicationContext(), "us-east-1:f847843f-0162-43c2-b73f-efdc7c69cce2", // Identity pool ID Regions.US_EAST_1 // Region );
Store User Data:
// Initialize the Cognito Sync client CognitoSyncManager syncClient = new CognitoSyncManager( getApplicationContext(), Regions.US_EAST_1, // Region credentialsProvider);
// Create a record in a dataset and synchronize with the server Dataset dataset = syncClient.openOrCreateDataset("myDataset"); dataset.put("myKey", "myValue"); dataset.synchronize(new DefaultSyncCallback() { @Override public void onSuccess(Dataset dataset, List newRecords) { //Your handler code here } });
- Note down the Identity pool id and region . In my case identity pool id is "us-east-1:f847843f-0162-43c2-b73f-efdc7c69cce2" and region is us-east-1. We will need it in subsequent setup.
The last part that is remaining now is to add additional permissions to our new role so that Cognito pool users can access other required AWS services - in this case since we need to upload files to S3 we just need S3 put access.
NOTE: Make sure Cognito identity pool should be created in same region as S3 bucket.
So go to IAM and go to roles and select it. Now click add inline policy and add following JSON policy -
You have to replace <BUCKET_NAME> with your actual S3 bucket name. Always make IAM policies as stricter as possible. In this case, we are just giving put object permission on the desired S3 bucket only.
NOTE: This was for upload to S3 bucket but you can provide access to other services that you desire. If you need to create the policy you can use policy generator AWS provides - https://awspolicygen.s3.amazonaws.com/policygen.html
NOTE: Make sure Cognito identity pool should be created in same region as S3 bucket.
So go to IAM and go to roles and select it. Now click add inline policy and add following JSON policy -
{ "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1526901559336", "Action": [ "s3:PutObject" ], "Effect": "Allow", "Resource": "arn:aws:s3:::<BUCKET_NAME>/*" } ] }
You have to replace <BUCKET_NAME> with your actual S3 bucket name. Always make IAM policies as stricter as possible. In this case, we are just giving put object permission on the desired S3 bucket only.
NOTE: This was for upload to S3 bucket but you can provide access to other services that you desire. If you need to create the policy you can use policy generator AWS provides - https://awspolicygen.s3.amazonaws.com/policygen.html
At this point, your Cognito service is all set up for implementation. In the next post, we will see how we can use this to implement it in our mobile or web application.
Related Links
- https://console.aws.amazon.com/cognito/home?region=us-east-1#
- https://awspolicygen.s3.amazonaws.com/policygen.html
- How to upload files to S3 from iOS app written in Objective C using AWS Cognito identity pool(OSFG)
- https://docs.aws.amazon.com/aws-mobile/latest/developerguide/how-to-integrate-an-existing-bucket.html
Good Post , Could you please share with us java code which you have used in the Demo
ReplyDelete