Aws Cognito Still Login After Delete the App
User Authentication with AWS Cognito
Amazon Cognito is a user hallmark service that enables user sign-up and sign-in, and access command for mobile and web applications, hands, chop-chop, and securely. In Amazon Cognito, you can create your user directory, which allows the application to work when the devices are not online and to save data on the user's device and synchronize it. It gives a consistent application experience to the user, regardless of the device.
Amazon Cognito supports, to calibration, millions of users and authenticates users from social identity providers such as Facebook, Google, Twitter, Amazon, or enterprise identity providers, such as Microsoft Active Directory through SAML, or your own identity provider system.
With Amazon Cognito, yous can concentrate on developing great application experiences for the user, instead of worrying near developing secure and scalable application solutions for handling the admission control permissions of users and synchronization across the devices.
Amazon Cognito benefits
- Amazon Cognito is a fully managed service and information technology provides User Pools for a secure user directory to scale millions of users; these User Pools are piece of cake to set.
- Amazon Cognito User Pools are standard-based identity providers, Amazon Cognito supports many identity and access direction standards such as OAuth 2.0, SAML 2.0, OAuth 2.0 and OpenID Connect.
- Amazon Cognito supports the encryption of information in transit or at residual, and multi-factor authentication.
- With Amazon Cognito, yous can command access to the backend resources from the application. You lot tin can control the users past defining roles and map different roles for the application, and then they can admission the application resources for which they are authorized.
- Amazon Cognito tin integrate easily with the sign-up and sign-in for the app because information technology provides a built-in UI and configuration for unlike federating identity providers. It provides the facility to customize the UI, as per company branding, in front and centre for user interactions.
- Amazon Cognito is eligible for HIPAA-BAA and is compliant with PCI DSS, SOC i–3, and ISO 27001.
Amazon Cognito features
1. Amazon Cognito User Pools
Amazon Cognito User Pools helps to create and maintain a directory for users and adds sign-up/sign-in to mobile or web applications. Users can sign in to a User Pool through social or SAML-based identity providers. It provides a secure, simple, low-cost pick and scales to millions of users.
Enhanced security features such as multi-factor authentication and email/phone number verification tin be implemented for your application. With AWS Lambda, you can customize your workflows for Amazon Cognito User Pools such as adding application specific logins for user validation and registration for fraud detection.
Getting started with Amazon Cognito User Pools
You can create Amazon Cognito User Pools through Amazon Cognito Panel, AWS Command Line Interface (CLI), or Amazon Cognito Application Programming Interface (API). At present allow's understand all these different ways of creating User Pools.
Amazon Cognito User Pool creation from the console
Please perform the following steps to create a User Pool from the console.
- Log in to the AWS Management console and select the Amazon Cognito service.
- It volition bear witness you two options, such as Manage your User Pools and Manage Federated Identities, as shown:
3. Select Manage Your User Pools. It volition accept y'all to the Create a user pool screen. You tin can add the Pool name and create the User Pool. You tin can create this user puddle in ii unlike ways, by selecting:
- Review defaults: It comes with default settings and if required, you can customize it
- Step through settings: Step by step, you tin can customize each setting:
4. When you lot select Review defaults, you lot will be taken to the review User Puddle configuration screen and then select Create puddle.
v. When yous will select Step through settings, yous volition taken to the Attributes screen to customize it. Let's understand all the screens in brief:
- Attributes: This gives the choice for users to sign in with a username, email address, or phone number. You tin select standard attributes for user profiles too create custom attributes.
- Policies: You tin set the password force, allow users to sign in themselves, and stipulate days until expire for the newly created business relationship.
- MFA and verifications: This allows you lot to enable Multi-Factor Authentication, and configure require verification for emails and telephone numbers. Y'all create a new IAM role to set permissions for Amazon Cognito that allows you to send SMS message to users on your behalf.
- Message customizations: You can customize messages to verify an email address by providing a verification code or link. You tin can customize user invitation messages for SMS and email just you must include the username and a temporary countersign. Yous can customize e-mail addresses from SES-verified identities.
- Tags: You can add tags for this User Puddle by providing tag keys and their values.
- Devices: This provides settings to retrieve a user's device. Information technology provides options such every bit Always, User Opt In, and No.
- App clients: You can add together app clients by giving unique IDs and an optional cloak-and-dagger key to access this User Puddle.
- Triggers: You lot can customize workflows and user experiences by triggering AWS Lambda functions for dissimilar events.
- Reviews: This shows you all the attributes for review.
6. You can edit any attribute on the Reviews screen so click on Create puddle. It will create the User Pool.
7. After creating a new User Puddle, navigate to the App clients screen. Enter the App client proper noun as CognitoDemo and click on Create app customer:
8. Once this Client App is generated, you can click on the show details to see App client secret:
9. Pool Id, App client id, and App customer secret are required to connect whatsoever application to Amazon Cognito.
Amazon Cognito case for Android with mobile SDK
In this example, we will perform some tasks such as create new user, request confirmation code for new user through electronic mail, confirm user, user login, and and so on.
- Create a Cognito User Pool:
To create a User Pool with the default configuration, you have to pass parameters to the CognitoUserPool constructor, such equally application context, userPoolId, clientId, clientSecret, and cognitoRegion(optional):
CognitoUserPool userPool = new CognitoUserPool(context, userPoolId, clientId, clientSecret, cognitoRegion);
- New user sign-up:
Delight perform the post-obit steps to sign up new users:
Collect information from users such as username, password, given proper name, phone number, and email address. Now, create the CognitoUserAttributes object and add the user value in a key-value pair to sign upwards for the user:
CognitoUserAttributes userAttributes = new CognitoUserAttributes(); String usernameInput = username.getText().toString();
Cord userpasswordInput = password.getText().toString();
userAttributes.addAttribute("Name", proper noun.getText().toString());
userAttributes.addAttribute("E-mail", email.getText().toString());
userAttributes.addAttribute("Phone", phone.getText().toString());
userPool.signUpInBackground(usernameInput, userpasswordInput, userAttributes, nothing, signUpHandler);
To annals or sign up a new user, you have to telephone call SignUpHandler. It contains two methods: onSuccessand onFailure.
For onSuccess, information technology will call when information technology successfully registers a new user. The user needs to ostend the lawmaking required to activate the account. You have to pass parameters such as Cognito user, confirm land of the user, medium and destination of the confirmation lawmaking, such every bit e-mail or phone, and the value for that:
SignUpHandler signUpHandler = new SignUpHandler() {
@Override
public void onSuccess(CognitoUser user, boolean signUpConfirmationState, CognitoUserCodeDeliveryDetails cognitoUserCodeDeliveryDetails) {
// Check if the user is already confirmed
if (signUpConfirmationState) {
showDialogMessage("New User Sign upwards successful!","Your Username is : "+usernameInput, true);
} } @Override
public void onFailure(Exception exception) {
showDialogMessage("New User Sign up failed.",AppHelper.formatException(exception),false);
}
};
You tin see on the User Puddle panel that the user has been successfully signed up simply non confirmed yet:
- Confirmation code request:
After successfully signing up, the user needs to confirm the code for sign-in. The confirmation code will exist sent to the user'south email or phone. Sometimes it may automatically confirm the user by triggering a Lambda function. If you lot selected automatic verification when you created the User Pool, it will send the confirmation code to your email or telephone. Yous tin can allow the user know where they will get the confirmation code from the cognitoUserCodeDeliveryDetails object.
It will indicate where you will send the confirmation lawmaking:
VerificationHandler resendConfCodeHandler = new VerificationHandler() {
@Override
public void onSuccess(CognitoUserCodeDeliveryDetails details) {
showDialogMessage("Confirmation code sent.","Code sent to "+details.getDestination()+" via "+details.getDeliveryMedium()+".", false);
} @Override
public void onFailure(Exception exception) {
showDialogMessage("Confirmation code request has failed", AppHelper.formatException(exception), simulated);
}
};
In this example, the user volition receive an electronic mail with the confirmation code:
The user can complete the sign-up process after inbound the valid confirmation lawmaking. To ostend the user, you lot need to call the GenericHandler. AWS SDK uses this GenericHandler to communicate the result of the confirmation API:
GenericHandler confHandler = new GenericHandler() {
@Override
public void onSuccess() {
showDialogMessage("Success!",userName+" has been confirmed!", truthful);
} @Override
public void onFailure(Exception exception) {
showDialogMessage("Confirmation failed", exception, false);
}
};
In one case the user confirms, it will be updated in the Amazon Cognito console:
- Sign in user to the app:
You must create an authentication callback handler for the user to sign in to your awarding. The following code volition show you how the interaction happens from your app and SDK:
// telephone call Authentication Handler for User sign-in process.
AuthenticationHandler authHandler = new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession cognitoUserSession) {
launchUser();
// call Authentication Handler for User sign-in procedure.
AuthenticationHandler authHandler = new AuthenticationHandler() {
@Override
public void onSuccess(CognitoUserSession cognitoUserSession) {
launchUser();
} @Override
public void getAuthenticationDetails(AuthenticationContinuation continuation, Cord username) {
// Get user sign-in credential information from API. AuthenticationDetails authDetails = new AuthenticationDetails(username, password, zippo);
// Ship this user sign-in information for continuation continuation.setAuthenticationDetails(authDetails);
// Allow user sign-in procedure to go on continuation.continueTask();
} @Override
public void getMFACode(MultiFactorAuthenticationContinuation mfaContinuation) {
// Become Multi-cistron authentication code from user to sign-in
mfaContinuation.setMfaCode(mfaVerificationCode);
// Allow user sign-in procedure to continue
mfaContinuation.continueTask();
} @Override
public void onFailure(Exception e) { // User Sign-in failed. Please cheque the exception
showDialogMessage("Sign-in failed", e);
} @Override
public void authenticationChallenge(ChallengeContinuation continuation) {
/** Yous tin implement Custom authentication claiming logic
* here. Pass the user's responses to the continuation.
*/
}
};
- Access AWS resources from application user:
A user tin can admission AWS resources from the application by creating an AWS Cognito Federated Identity Puddle and associating an existing User Pool with that Identity Pool, by specifying User Pool ID and App customer id.
Let'southward continue with the aforementioned application; after the user is authenticated, add the user's identity token to the logins map in the credential provider. The provider name depends on the Amazon Cognito User Pool ID and it should have the following structure:
cognito-idp.<USER_POOL_REGION>.amazonaws.com/<USER_POOL_ID>
For this case, it will exist: cognito-idp.u.s.a.-eastward-1.amazonaws.com/usa-east-1_XUGRPHAWA.
Now, in your credential provider, pass the ID token that you become after successful authentication:
// Later successful authentication get id token from
// CognitoUserSession
Cord idToken = cognitoUserSession.getIdToken().getJWTToken(); // Employ an existing credential provider or create new
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(context, IDENTITY_POOL_ID, REGION);
// Credentials provider setup
Map<String, String> logins = new HashMap<String, String>();
logins.put("cognito-idp.united states of america-east-1.amazonaws.com/united states of america-e-1_ XUGRPHAWA", idToken);
credentialsProvider.setLogins(logins);
You can use this credential provider to access AWS services, such as Amazon DynamoDB, every bit follows:
AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(credentialsProvider)
Amazon Cognito Federated Identities
Amazon Cognito Federated Identities enables yous to create unique identities for the user and, authenticate with Federated Identity providers.
With this identity, the user will become temporary, express-privileged AWS credentials. With these credentials, the user tin can synchronize their data with Amazon Cognito Sync or securely admission other AWS services such as Amazon S3, Amazon DynamoDB, and Amazon API Gateway.
Creating a new Identity Pool from the console
Please perform the following steps to create a new Identity Puddle from the panel:
- Log in to the AWS Management console and select the Amazon Cognito Service.
- It will show you two options: Manage your User Pools and Manage Federated Identities.
- Select Manage Federated Identities. It will navigate you to the Create new identity pool screen. Enter a unique name for the Identity pool proper name:
4. You can enable unauthenticated identities by selecting Enable admission to unauthenticated identities from the collapsible section:
five. Under Authentication providers, yous can allow your users to authenticate using any of the authentication methods. Click on Create puddle.
Hither Cognito has been selected for a valid Authentication provider by adding User Pool ID and App customer id:
6. Information technology will navigate to the next screen to create a new IAM office by default, to provide express permission to end users. These permissions are for Cognito Sync and Mobile Analytics but you tin edit policy documents to add/update permissions for more services. Information technology will create 2 IAM roles. 1 for authenticated users that are supported by identity providers and some other for unauthenticated users, known as guest users. Click Permit to generate the Identity Pool:
7. One time the Identity Pool is generated, information technology will navigate to the Getting started with Amazon Cognito screen for that Identity Pool. Hither, it will provide you with downloadable AWS SDK for unlike platforms such equally Android, iOS — Objective C, iOS — Swift, JavaScript, Unity, Xamarin, and .NET. It also provides sample code for Get AWS Credentials and Store User Data:
Amazon Cognito Sync
Amazon Cognito Sync is an AWS Service used to synchronize the information across client devices, platforms, and operating systems.
Amazon Cognito Sync supports cantankerous-device sync and the offline access of a user'due south application-related data. Information technology can exist used to synchronize a user'due south profile information as well as across mobile and web applications, without requiring your backend organisation.
It contains a customer library to cache data locally that is used to read and write data, without any device connectivity status. Yous can synchronize the data when the device is online and you lot can fix push synchronization to notify other devices whenever any update is available.
Amazon Cognito saves cease-user data as key-value pairs in datasets. This data is associated with Amazon Cognito Identity and it can exist accessed across different devices and logins. The synchronize method is invoked to sync the data between an cease user's device and Amazon Cognito. The maximum size of each dataset is one MB, and you can associate an identity with upwards to 20 datasets.
You lot need to create a credential provider to initialize the Amazon Cognito Sync client. This credential provider gets temporary AWS credentials to enable the app to access your AWS resources.
Y'all tin utilize the following code to initialize the Amazon Cognito Sync client in Android.
You need to import the Amazon Cognito package:
import com.amazonaws.mobileconnectors.cognito.*;
Now, initialize the Amazon Cognito Sync Director by providing the Android app context, an AWS region, and an Amazon Cognito credential provider:
CognitoSyncManager customer = new CognitoSyncManager
(getApplicationContext(), Regions.YOUR_REGION, credentialsProvider);
With Amazon Cognito, your app'southward profile data is organized into datasets. This dataset is the granular entity to perform the sync operation and it is a unique string. Read and write operations on datasets will bear on the local shop, until the synchronize method is invoked.
The post-obit code will create a new dataset or open an existing dataset:
Dataset dataset = client.openOrCreateDataset("my_dataset_name");
Amazon Cognito datasets office as dictionaries and are accessible through keys with values.
String value = dataset.get("myKey");
// Yous can call put to put the key in dataset
dataset.put("myKey", "my value");
// You tin telephone call remove to remove the fundamental from dataset
dataset.remove("myKey");
You tin call synchronize to compare Amazon Cognito Sync store data with local cache information. Amazon Cognito Sync volition pull the remote changes, disharmonize the resolution, if any, and update the values on the service which are pushed from the device. You tin call synchronize dataset by calling its synchronize method:
dataset.synchronize(syncCallback);
When connectivity is available immediately, synchronizeOnConnectivity() will behave as synchronize() and if it'south not available, information technology will monitor for connectivity change and perform a sync when connectivity is bachelor.
When synchronizeOnConnectivity() calls multiple times, then only the final synchronize request is kept and callback will fire.
This method will not perform sync and callback will not fire, if the dataset or the callback has collected garbage.
To delete the dataset from Amazon Cognito, you first remove the dataset from local storage and and then call the synchronize() method:
dataset.delete();
dataset.synchronize(syncCallback);
Now, let's understand how to handle a callback.
You can implement the SyncCallback interface to receive a notification in the app. Your app can make the decision to delete the local data, merge authenticated and unauthenticated profiles, and resolve the synchronization conflicts. You tin can implement the following methods:
- onSuccess(): It will trigger when a dataset is downloaded successfully from the sync store:
@Override
public void onSuccess(Dataset dataset, List<Tape> newRecords) {}
- onFailure(): It will telephone call if an exception occurs during synchronization:
@Override
public void onFailure(DataStorageException dse) {}
- onConflict(): It might happen that the same key has been modified in the local shop and in the sync store. This onConflict() method helps to handle this kind of conflict situation. If you practice not implement this method, and then Amazon Cognito Sync will use the nearly recent changes:
@Override
public boolean onConflict(Dataset dataset, last List<SyncConflict> conflicts) {
List<Tape> resolveRecord = new ArrayList<Record>();
for (SyncConflict conflict : conflicts) {
// Taking remote records to resolve conflicts
resolveRecord.add(disharmonize.resolveWithRemoteRecord());
}
dataset.resolve(resolveRecord); // synchronize() volition retry after conflicts resolved
return true;
}
- onDatasetDeleted(): In one case the dataset is deleted, information technology should likewise delete the local dataset, and the Amazon Cognito customer uses the SyncCallback interface to confirm it. What you can practice with the local information is that yous tin can tell the client SDK by implementing the onDatasetDeleted() method:
@Override
public boolean onDatasetDeleted(Dataset dataset, String datasetName) {
// Render truthful to delete local dataset copy
return true;
}
- onDatasetsMerged(): All the datasets are merged when 2 unconnected or disconnected identities are linked together. Yous tin can notify the application to merge by calling the onDatasetsMerged() method:
@Override
public boolean onDatasetsMerged(Dataset dataset, List<String> datasetNames) {
// Return faux if Dataset merge outside the synchronization callback
return false;
}
In Amazon Cognito, the association between the device and identity can rail automatically. You tin can sure that every instance of the identity is notified when information technology identifies any changes using push synchronization or push sync. Push sync confirms that whenever whatsoever changes occur in sync store data for a particular identity, then it volition automatically send the silent push notification to other devices associated with that identity.
To enable Push Sync for your awarding, you lot demand to create and configure an Amazon SNS app for the supported platform and select the service role in the Federated Identities page for Push Synchronization:
You can use the following keys for the push notification payload:
- source: cognito-sync is the differentiating factor between notifications
- identityPoolId: The Identity Puddle ID, used for validation or additional information
- identityId: Identity ID within the pool
- datasetName: Name of the dataset which was updated
- syncCount: The sync count for the remote dataset
Summary
So far, nosotros take looked at AWS Cognito with User Pools, Federated Identities, and Cognito Sync.
In the adjacent blog, we will talk over three main architectures: EC2 instance with Load Balancer, Docker, and Serverless, and look at the differences between them.
Aws Cognito Still Login After Delete the App
DOWNLOAD HERE
Source: https://medium.com/@pavithra_38952/user-authentication-with-aws-cognito-4718e7f0ed0a
Posted by: 7news2onlinea.blogspot.com
comment 0 comments
more_vert