View a markdown version of this page

Getting credentials - Amazon Cognito
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Getting credentials

You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application, so that your users can access Amazon resources. This section describes how to get credentials and how to retrieve an Amazon Cognito identity from an identity pool.

Amazon Cognito supports both authenticated and unauthenticated identities. Unauthenticated users do not have their identity verified, making this role appropriate for guest users of your app or in cases when it doesn't matter if users have their identities verified. Authenticated users log in to your application through a third-party identity provider, or a user pool, that verifies their identities. Make sure you scope the permissions of resources appropriately so you don't grant access to them from unauthenticated users.

Amazon Cognito identities are not credentials. They are exchanged for credentials using web identity federation support in the Amazon Security Token Service (Amazon STS). To obtain Amazon credentials for your app users, use your Amazon SDK's Cognito identity pool credential provider. For example, in the Amazon SDK for JavaScript (v3), use the fromCognitoIdentityPool function from the @aws-sdk/credential-providers package. The identity is then exchanged for credentials using Amazon STS.

Web identity credentials providers are part of the default credential provider chain in Amazon SDKs. To set your identity pool token in a local config file for an Amazon SDK or the Amazon CLI, add a web_identity_token_file profile entry. See Assume role credential provider in the Amazon SDKs and Tools Reference Guide.

To learn more about how to populate web identity credentials in your SDK, refer to the SDK developer guide. For best results, start your project with the identity pool integration that's built in to Amazon Amplify.

Amazon SDK resources for getting and setting credentials with identity pools

The following sections provide example code in some legacy Amazon SDKs.

You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application, so that your users can access Amazon resources. Amazon Cognito supports both authenticated and unauthenticated identities. To provide Amazon credentials to your app, follow these steps.

To use a Amazon Cognito identity pool in an Android app, set up Amazon Amplify. For more information, see Authentication in the Amplify Dev Center.

Retrieving an Amazon Cognito identity

If you're allowing unauthenticated users, you can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately. If you're authenticating users, you can retrieve the identity ID after you've set the login tokens in the credentials provider:

String identityId = credentialsProvider.getIdentityId(); Log.d("LogTag", "my ID is " + identityId);
Note

Do not call getIdentityId(), refresh(), or getCredentials() in the main thread of your application. As of Android 3.0 (API Level 11), your app will automatically fail and throw a NetworkOnMainThreadException if you perform network I/O on the main application thread. You must move your code to a background thread using AsyncTask. For more information, consult the Android documentation. You can also call getCachedIdentityId() to retrieve an ID, but only if one is already cached locally. Otherwise, the method will return null.

You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application, so that your users can access Amazon resources. Amazon Cognito identity pools support both authenticated and unauthenticated identities. To provide Amazon credentials to your app, complete the following steps.

To use a Amazon Cognito identity pool in an iOS app, set up Amazon Amplify. For more information, see Swift Authentication and Flutter Authentication in the Amplify Dev Center.

Retrieving an Amazon Cognito identity

You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately if you're allowing unauthenticated users or after you've set the login tokens in the credentials provider if you're authenticating users:

// Retrieve your Amazon Cognito ID [[credentialsProvider getIdentityId] continueWithBlock:^id(AWSTask *task) { if (task.error) { NSLog(@"Error: %@", task.error); } else { // the task result will contain the identity id NSString *cognitoId = task.result; } return nil; }];
Note

getIdentityId is an asynchronous call. If an identity ID is already set on your provider, you can call credentialsProvider.identityId to retrieve that identity, which is cached locally. However, if an identity ID is not set on your provider, calling credentialsProvider.identityId returns nil. For more information, consult the Amplify iOS SDK reference.

You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application so that your users can access Amazon resources. Amazon Cognito supports both authenticated and unauthenticated identities. To provide Amazon credentials to your app, follow these steps.

To use a Amazon Cognito identity pool in an iOS app, set up Amazon Amplify. For more information, see Swift Authentication in the Amplify Dev Center.

Retrieving an Amazon Cognito identity

You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately if you're allowing unauthenticated users or after you've set the login tokens in the credentials provider if you're authenticating users:

// Retrieve your Amazon Cognito ID credentialsProvider.getIdentityId().continueWith(block: { (task) -> AnyObject? in if (task.error != nil) { print("Error: " + task.error!.localizedDescription) } else { // the task result will contain the identity id let cognitoId = task.result! print("Cognito id: \(cognitoId)") } return task; })
Note

getIdentityId is an asynchronous call. If an identity ID is already set on your provider, you can call credentialsProvider.identityId to retrieve that identity, which is cached locally. However, if an identity ID is not set on your provider, calling credentialsProvider.identityId returns nil. For more information, consult the Amplify iOS SDK reference.

If you have not yet created one, create an identity pool in the Amazon Cognito console before using fromCognitoIdentityPool.

After you configure an identity pool with your identity providers, you can use the fromCognitoIdentityPool function from the @aws-sdk/credential-providers package to authenticate users. Rather than setting a global AWS.config.credentials, attach the credentials provider directly to each service client through its credentials property. The v3 SDK resolves the provider lazily the first time the client makes a request, so there is no separate call to obtain credentials. The following example attaches the provider to an S3Client:

import { S3Client } from "@aws-sdk/client-s3"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers"; // Set the region where your identity pool exists (for example, us-east-1 or eu-west-1) const region = "REGION"; // Attach the credentials provider to your service client const client = new S3Client({ region, credentials: fromCognitoIdentityPool({ identityPoolId: "IDENTITY_POOL_ID", logins: { // optional tokens, used for authenticated login "graph.facebook.com": "FBTOKEN", "www.amazon.com": "AMAZONTOKEN", "accounts.google.com": "GOOGLETOKEN", "appleid.apple.com": "APPLETOKEN" }, clientConfig: { region }, }), }); // Credentials are resolved lazily when the client first makes a request. // To inspect them directly, call the provider and await the result // (from inside an async function): const credentials = await client.config.credentials(); const { accessKeyId, secretAccessKey, sessionToken } = credentials;

The optional logins property is a map of identity provider names to the identity tokens for those providers. How you get the token from your identity provider depends on the provider you use. For example, if Facebook is one of your identity providers, you might use the FB.login function from the Facebook SDK to get an identity provider token:

FB.login(function (response) { if (response.authResponse) { // logged in const region = "us-east-1"; const client = new S3Client({ region, credentials: fromCognitoIdentityPool({ identityPoolId: "us-east-1:1699ebc0-7900-4099-b910-2df94f52a030", logins: { "graph.facebook.com": response.authResponse.accessToken }, clientConfig: { region }, }), }); console.log('You are now logged in.'); } else { console.log('There was a problem logging you in.'); } });

Retrieving an Amazon Cognito identity

You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user. If you allow unauthenticated users, you can retrieve it immediately. If you authenticate users, retrieve it after you set the login tokens. The fromCognitoIdentityPool provider exposes the identityId on the credentials that it resolves, so you can read it from the resolved credentials of a client that uses the provider:

// Inside an async function: const { identityId } = await client.config.credentials();

You can use Amazon Cognito to deliver temporary, limited-privilege credentials to your application, so that your users can access Amazon resources. Amazon Cognito supports both authenticated and unauthenticated identities. To provide Amazon credentials to your app, follow these steps.

The Amazon SDK for Unity is now part of the Amazon SDK for .NET. To get started with Amazon Cognito in the Amazon SDK for .NET, see Amazon Cognito credentials provider in the Amazon SDK for .NET Developer Guide. Or see Amplify Dev Center for options for building an app with Amazon Amplify.

Retrieving an Amazon Cognito identity

You can retrieve a unique Amazon Cognito identifier (identity ID) for your end user immediately if you're allowing unauthenticated users or after you've set the login tokens in the credentials provider if you're authenticating users:

string identityId = await credentials.GetIdentityIdAsync();