4.2 Authenticate Using AWS Cognito Service Wrapper
If you are using AWS Cognito Service for user authentication, AWS Cognito Service Wrapper lets you authenticate with AWS Cognito and Bayun together. You don't need to authenticate with Bayun separately, you can use the Bayun AWS Cognito Service Wrapper APIs to signIn/signUp with AWS Cognito. Bayun AWS Cognito Service Wrapper APIs take care of the authentication with Bayun.
Let us first look at how a typical app is created using user pools with the AWS Mobile SDK for iOS and then look at the components of the S3 app that get affected using Bayun AWSS3 wrapper class SecureAuthentication
.
4.2.1 Using user pools with AWS Mobile SDK
Here are the details about registering, confirming, and authenticating users using standard AWS Mobile SDK.
Creating an AWSCognitoIdentityUserPool Object
The following procedure describes how to create an AWSCognitoIdentityUserPool object to interact with.
// Create a user pool with default ClientConfiguration
CognitoUserPool userPool = new CognitoUserPool(context, userPoolId, clientId, clientSecret, cognitoRegion);
OR
// This will also work
ClientConfiguration clientConfiguration = new ClientConfiguration();
AmazonCognitoIdentityProvider cipClient = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), clientConfiguration);
cipClient.setRegion(Region.getRegion(cognitoRegion));
CognitoUserPool userPool = new CognitoUserPool(context, userPoolId, clientId, clientSecret, cipClient);
Register a User
Use userPool.signUpInBackground
method to sign up a user.
// create a handler for registration
SignUpHandler signupCallback = new SignUpHandler() {
@Override
public void onSuccess(CognitoUser cognitoUser, boolean userConfirmed, CognitoUserCodeDeliveryDetails cognitoUserCodeDeliveryDetails) {
// Sign-up was successful
// Check if this user (cognitoUser) needs to be confirmed
if(!userConfirmed) {
// This user must be confirmed and a confirmation code was sent to the user
// cognitoUserCodeDeliveryDetails will indicate where the confirmation code was sent
// Get the confirmation code from user
}
else {
// The user has already been confirmed
}
}
@Override
public void onFailure(Exception exception) {
// Sign-up failed, check exception for the cause
}
};
// API call
userPool.signUpInBackground(userId, password, userAttributes, null, signupCallback);
Confirm Signup
Confirm a user's sign up with the confirmation code using user.confirmSignUp
method
// create a callback handler for confirm
GenericHandler handler = new GenericHandler() {
@Override
public void onSuccess() {
// User was successfully confirmed!
}
@Override
public void onFailure(Exception exception) {
// Confirmation failed, probe exception for details
}
}
// API call
user.confirmSignUp(code, handler);
Sign in a User
Use cognitoUser.getSessionInBackground
method to get a session with the username and password.
// Callback handler for the sign-in process
AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession cognitoUserSession) {
// Sign-in was successful, cognitoUserSession will contain tokens for the user
}
@Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, password, null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
@Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Multi-factor authentication is required; get the verification code from user
multiFactorAuthenticationContinuation.setMfaCode(mfaVerificationCode);
// Allow the sign-in process to continue
multiFactorAuthenticationContinuation.continueTask();
}
@Override
public void onFailure(Exception exception) {
// Sign-in failed, check exception for the cause
}
};
// Sign in the user
cognitoUser.getSessionInBackground(authenticationHandler);
Sign out a user
Use cognitoUser.signOut
method to log a user out.
// This has cleared all tokens and this user will have to go through the authentication process to get tokens.
user.signOut();
4.2.2 Using user pools with Bayun AWSS3 wrapper 'SecureAuthentication'
User Registration, SignUp Confirmation, SignIn, SignOut needs to be done with SecureAuthentication instance.
Set up your service config
There is no change in setting up Service Config and is same as using standard AWS Mobile SDK.
// Create a user pool with default ClientConfiguration
CognitoUserPool userPool = new CognitoUserPool(context, userPoolId, clientId, clientSecret, cognitoRegion);
OR
// This will also work
ClientConfiguration clientConfiguration = new ClientConfiguration();
AmazonCognitoIdentityProvider cipClient = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), clientConfiguration);
cipClient.setRegion(Region.getRegion(cognitoRegion));
CognitoUserPool userPool = new CognitoUserPool(context, userPoolId, clientId, clientSecret, cipClient);
Set Up the SecureAuthentication object
The SecureAuthentication is a singleton object, and must be provided with context, appId and companyName before using it. This will serve as the object on which all function calls are to be made.
secureAuthentication = SecureAuthentication.getInstance();
secureAuthentication.setContext(appContext);
secureAuthentication.setAppId(APP_ID);
secureAuthentication.setCompanyName(companyName);
Register a User
Use SecureAuthentication's method signUp
to register a new user instead of relying on standard AWS Mobile SDK's signUp method.
// Hashmap to save the signup fields
HashMap signUpFields = new HashMap<String, String>();
// Read user data and register
CognitoUserAttributes userAttributes = new CognitoUserAttributes();
userAttributes.addAttribute(signUpFields.put("Given name", given_name);
userAttributes.addAttribute(signUpFields.put("Email", "
[email protected]");
//phone number must be prefixed by country code
userAttributes.addAttribute(signUpFields.put("Phone number", "+15555555555");
// SignupHandler to handle signup outcomes.
SignUpHandler signUpHandler = new SignUpHandler() {
@Override
public void onSuccess(CognitoUser user, boolean signUpConfirmationState, CognitoUserCodeDeliveryDetails cognitoUserCodeDeliveryDetails) {
if (signUpConfirmationState) {
// User is already confirmed
// handle the case where user identity is already confirmed.
}
else {
// User is not confirmed
// handle the case where user has to confirm his identity
}
}
@Override
public void onFailure(Exception exception) {
// Handle failure.
}
};
// Signup call
SecureAuthentication.getInstance().signUp(activityContext, userPool, usernameInput, userpasswordInput, userAttributes, null, signUpHandler);
Confirm Signup
Confirm a users' sign up with the confirmation code using SecureAuthentication's confirmSignUp
method. Use this method instead of CognitoUser
's method, to confirm signup with both Cognito and Bayun.
// Call to confirm the user.
SecureAuthentication.getInstance().confirmSignUp(activityContext, cognitoUser, confirmCode, forcedAliasCreation, confHandler);
// Callback to handle the confirmation api call.
GenericHandler confHandler = new GenericHandler() {
@Override
public void onSuccess() {
Log.d(TAG, "User confirmed.");
// Handle success.
}
@Override
public void onFailure(Exception exception) {
// Handle failure.
}
};
Sign in a user
Use SecureAuthentication's signIn
method to get a session, using username and password, with both Cognito and Bayun, instead of CognitoUser
's method.
// Call to sign in a user.
SecureAuthentication.getInstance().signIn(activityContext, username, password, cognitoUser, authenticationHandler);
// Callback to handle the signIn api call.
AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession cognitoUserSession, CognitoDevice device) {
Log.d(TAG, "User sign in success.");
// Handle success.
// This block is also executed when a user is already signed in.
}
@Override
public void getAuthenticationDetails(AuthenticationContinuation continuation, String username) {
AuthenticationDetails authenticationDetails = new AuthenticationDetails(username, password, validationData);
continuation.setAuthenticationDetails(authenticationDetails);
continuation.continueTask();
}
@Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Handle this block, if needed.
}
@Override
public void onFailure(Exception e) {
// Handle failure.
}
@Override
public void authenticationChallenge(ChallengeContinuation continuation) {
/**
* For Custom authentication challenge, implement your logic to present challenge to the
* user and pass the user's responses to the continuation.
*/
}
};
Sign out a user
Use SecureAuthentication's signOut
method to clear all tokens and logout of Bayun as well, instead of using CognitoUser
's method. User will have to go through the authentication process to get tokens.
SecureAuthentication.getInstance().signOut(cognitoUser);