What is Amazon Cognito? 

Amazon Cognito is a simple user identity and data synchronization service that provides authentication, authorization, and user management, helping us securely manage app data across applications for our users.

Amazon Cognito allows us to control permissions for different user groups in our applications to ensure that they have appropriate access to back-end AWS resources.

Table of Content :

aws user signup in cognito pool

Maven dependencies

<dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-core</artifactId> <version>1.11.764</version> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-cognitoidp</artifactId> <version>1.11.764</version> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk</artifactId> <version>1.11.360</version> </dependency>

We need to log in to the AWS console and create a user pool.
With a user pool, your users can sign in to your web or mobile app through Amazon Cognito.

To create a user pool

1). Go to the Amazon Cognito console. You may be prompted for your AWS credentials.
2). Choose Manage User Pools.
3). Choose to Create a user pool.
4). Provide a name for your user pool and choose Review defaults to save the name.
5). On the Review page, choose Create pool.

For more in details , please read this - Create a Cognito user pool in AWS Console

We need pool Id, Client Id, Region, and AWS Access Key and Secret Key.

We have user POJO to create users in the pool.

import java.util.List; public class User { private String username; private String password; private List <UserAttributes > userAttributes; private List <CustomAttributes > customAttributes; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List <UserAttributes > getUserAttributes() { return userAttributes; } public void setUserAttributes(List <UserAttributes > userAttributes) { this.userAttributes = userAttributes; } public List <CustomAttributes > getCustomAttributes() { return customAttributes; } public void setCustomAttributes(List <CustomAttributes > customAttributes) { this.customAttributes = customAttributes; } }

We have User attribute POJO

public class UserAttributes { private String key; private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }

We have Custom Attributes

public class CustomAttributes { private String key; private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }

We have Cognito client to interact with AWS services

public static AWSCognitoIdentityProvider getAWSCognitoIdentityClient() { System.setProperty("aws.accessKeyId", "-- your accessKey Id--"); System.setProperty("aws.secretKey", "-- your secret Key--"); AWSCognitoIdentityProvider cognitoClient = AWSCognitoIdentityProviderClientBuilder.standard().withRegion(Regions.AP_SOUTH_1).withCredentials(new SystemPropertiesCredentialsProvider()).build(); return client; }

Here is our main class

import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.auth.SystemPropertiesCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProvider; import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProviderClientBuilder; import com.amazonaws.services.cognitoidp.model.AdminAddUserToGroupRequest; import com.amazonaws.services.cognitoidp.model.AdminConfirmSignUpRequest; import com.amazonaws.services.cognitoidp.model.AdminConfirmSignUpResult; import com.amazonaws.services.cognitoidp.model.AdminUpdateUserAttributesRequest; import com.amazonaws.services.cognitoidp.model.AdminUpdateUserAttributesResult; import com.amazonaws.services.cognitoidp.model.AttributeType; import com.amazonaws.services.cognitoidp.model.AuthFlowType; import com.amazonaws.services.cognitoidp.model.InitiateAuthRequest; import com.amazonaws.services.cognitoidp.model.InitiateAuthResult; import com.amazonaws.services.cognitoidp.model.ListUsersInGroupRequest; import com.amazonaws.services.cognitoidp.model.ListUsersInGroupResult; import com.amazonaws.services.cognitoidp.model.SignUpRequest; import com.amazonaws.services.cognitoidp.model.SignUpResult; import com.amazonaws.services.cognitoidp.model.UserType; import com.amazonaws.util.StringUtils; public class SignUpByConfirmEmail { private static final String clientId = "--your clientId--"; private static final String userPoolId = "--your user pool Id--"; public static void main(String[] args) { User user = new User(); user.setUsername("bala-user"); user.setPassword("Bala@345"); List <UserAttributes > userAttributesList = new ArrayList <UserAttributes >(); UserAttributes emailAttribute = new UserAttributes(); emailAttribute.setKey("email"); emailAttribute.setValue("bala.xxx@gmail.com"); userAttributesList.add(emailAttribute); UserAttributes phoneAttribute = new UserAttributes(); phoneAttribute.setKey("phone_number"); phoneAttribute.setValue("+911234567890"); userAttributesList.add(phoneAttribute); UserAttributes addAttribute = new UserAttributes(); addAttribute.setKey("address"); addAttribute.setValue("Vanaz Corner,Kothrud Pune-411038"); userAttributesList.add(addAttribute); UserAttributes genderAttribute = new UserAttributes(); genderAttribute.setKey("gender"); genderAttribute.setValue("male"); userAttributesList.add(genderAttribute); List <CustomAttributes > customAttributeList = new ArrayList <CustomAttributes >(); CustomAttributes designationAttribute = new CustomAttributes(); designationAttribute.setKey("designation"); designationAttribute.setValue("Manager"); customAttributeList.add(designationAttribute); signUpUser(User user); //signInUser("bala-user","Bala@345"); }

SignUp User in pool

public static signUpUser(User user) { String username = userbean.getUsername(); String password = userbean.getPassword(); for (UserAttributes userAttribute: userAttributeList) { String key = userAttribute.getKey(); String value = userAttribute.getValue(); AttributeType customAttributeType = new AttributeType().withName(key).withValue(value); userAttributes.add(customAttributeType); } for (CustomAttributes customAttribute: customAttributeList) { String key = customAttribute.getKey(); String value = customAttribute.getValue(); AttributeType customAttributeType = new AttributeType().withName(key).withValue(value); userAttributes.add(customAttributeType); } SignUpRequest signUpRequest = new SignUpRequest().withClientId(clientId).withUsername(username). withPassword(password).withUserAttributes(userAttributes); SignUpResult signUpResult = getAWSCognitoIdentityClient().signUp(signUpRequest); if (result != null) { String accessToken = ""; if (StringUtils.isNullOrEmpty(result.getChallengeName())) { System.out.println("User need to confirm using link recieved on the email "); } else { System.out.println("Some Challenges still exists while sign-in"); } }

After the user confirmed from the email link. Users can use a given username and password to log in. Using this login users get access token which contains temporary AWS credentials valid for 30 minutes.

Using these credentials users can access AWS services, permission is given to the AWS Cognito pool.

Login user to Cognito user Pool

public static InitiateAuthResult signInUserToAWSCognitoPool(String username, String password) { try { AWSCognitoIdentityProvider cognitoClient = getAWSCognitoIdentityClient(); final Map <String, String > authParams = new HashMap <String, String >(); authParams.put("USERNAME", username); authParams.put("PASSWORD", password); final InitiateAuthRequest initiateAuthRequest = new InitiateAuthRequest().withClientId(clientId).withAuthFlow(AuthFlowType.USER_PASSWORD_AUTH).withAuthParameters(authParams); final InitiateAuthResult result = cognitoClient.initiateAuth(initiateAuthRequest); System.out.println("InitiateAuthResult is" + result); //result contains session ,accessToken ,auth token etc } catch(Exception e) { System.out.println("Exception occured during sign up user : " + e); } return null; }

Add User to Group

Support for groups in Amazon Cognito user pools enables you to create and manage groups, add users to groups, and remove users from groups. Use groups to create collections of users to manage their permissions or to represent different types of users.
You can assign an AWS Identity and Access Management (IAM) role to a group to define the permissions for members of a group. Using that role permissions users can access AWS resources.

You can use groups to create a collection of users in a user pool, which is often done to set the permissions for those users. For example, you can create separate groups for users who are readers, contributors, and editors of your website and app.
Using the IAM role associated with a group, you can also set different permissions for those different groups so that only contributors can put content into Amazon S3 and only editors can publish content through an API in Amazon API Gateway.

You can create and manage groups in a user pool from the AWS Management Console, the APIs, and the CLI. As a developer (using AWS credentials), you can create, read, update, delete, and list the groups for a user pool. You can also add users and remove users from groups.

public static void addUserToGroup(String username, String groupname) { AWSCognitoIdentityProvider cognitoClient = getAWSCognitoIdentityClient(); AdminAddUserToGroupRequestaddUserToGroupRequest = new AdminAddUserToGroupRequest().withGroupName(groupname).withUserPoolId(userPoolId)).withUsername(username); cognitoClient.adminAddUserToGroup(addUserToGroupRequest); cognitoClient.shutdown(); }

In this article, we have seen AWS Cognito SignUp and SignIn Example Using Java . All source code in the article can be found in the GitHub repository.