

# Accessing resources after successful sign-in
Accessing resources after sign-in

Your app users can either sign in directly through a user pool, or they can federate through a third-party identity provider (IdP). The user pool manages the overhead of handling the tokens that are returned from social sign-in through Facebook, Google, Amazon, and Apple, and from OpenID Connect (OIDC) and SAML IdPs. For more information, see [Understanding user pool JSON web tokens (JWTs)](amazon-cognito-user-pools-using-tokens-with-identity-providers.md). 

After a successful authentication, your app will receive user pool tokens from Amazon Cognito. You can use user pool tokens to:
+ Retrieve AWS credentials that authorize requests for application resources in AWS services like Amazon DynamoDB and Amazon S3.
+ Provide temporary, revocable proof of authentication.
+ Populate identity data to a user profile in your app.
+ Authorize changes to the signed-in user's profile in the user pool directory.
+ Authorize requests for user information with an access token.
+ Authorize requests to data that is behind access-protected external APIs with access tokens.
+ Authorize access to application assets that are stored on the client or server with Amazon Verified Permissions.

For more information, see [An example authentication session](authentication.md#amazon-cognito-user-pools-authentication-flow) and [Understanding user pool JSON web tokens (JWTs)](amazon-cognito-user-pools-using-tokens-with-identity-providers.md).

![\[Authentication overview.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/scenario-authentication-cup.png)


**Topics**
+ [

# Authorizing access to client or server resources with Amazon Verified Permissions
](scenario-backend.md)
+ [

# Accessing resources with API Gateway after sign-in
](user-pool-accessing-resources-api-gateway-and-lambda.md)
+ [

# Accessing AWS services using an identity pool after sign-in
](amazon-cognito-integrating-user-pools-with-identity-pools.md)

# Authorizing access to client or server resources with Amazon Verified Permissions
Accessing resources with Verified Permissions

Your app can pass the tokens from a signed-in user to [Amazon Verified Permissions](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/what-is-avp.html). Verified Permissions is a scalable, fine-grained permissions management and authorization service for applications that you've built. An Amazon Cognito user pool can be an identity source to a Verified Permissions policy store. Verified Permissions makes authorization decisions for requested actions and resources, like `GetPhoto` for `premium_badge.png`, from the principal and their attributes in user pool tokens.

The following diagram shows how your application can pass a user's token to Verified Permissions in an authorization request.

![\[A flow diagram of an application that authenticates with an Amazon Cognito user pool and authorizes access to local resources with Amazon Verified Permissions.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/access-services-local-resources.png)


**Get started with Amazon Verified Permissions**  
After you integrate your user pool with Verified Permissions, you gain a central source of granular authorization for all of your Amazon Cognito apps. This removes the need for fine-grained security logic that you would otherwise have to code and replicate between all of your apps. For more information about authorization with Verified Permissions, see [Authorization with Amazon Verified Permissions](amazon-cognito-authorization-with-avp.md).

Verified Permissions authorization requests require AWS credentials. You can implement some of the following techniques to safely apply credentials to authorization requests.
+ Operate a web application that can store secrets in the server backend.
+ Acquire authenticated identity pool credentials.
+ Proxy user requests through an access-token-authorized API, and append AWS credentials to the request.

# Accessing resources with API Gateway after sign-in
Accessing API Gateway resources

A common use of Amazon Cognito user pools tokens is to authorize requests to an [API Gateway REST API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html). The OAuth 2.0 scopes in access tokens can authorize a method and path, like `HTTP GET` for `/app_assets`. ID tokens can serve as generic authentication to an API and can pass user attributes to the backend service. API Gateway has additional custom authorization options like [JWT authorizers for HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html) and [Lambda authorizers](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html) that can apply more fine-grained logic.

The following diagram illustrates an application that is gaining access to a REST API with the OAuth 2.0 scopes in an access token.

![\[A flow diagram of an application that authenticates with an Amazon Cognito user pool and authorizes access to API resources with Amazon API Gateway.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/access-services-api-gateway.png)


Your app must collect the tokens from authenticated sessions and add them as bearer tokens to an `Authorization` header in the request. Configure the authorizer that you configured for the API, path, and method to evaluate token contents. API Gateway returns data only if the request matches the conditions that you set up for your authorizer. 

Some potential ways that API Gateway API can approve access from an application are:
+ The access token is valid, isn't expired, and contains the correct OAuth 2.0 scope. The [Amazon Cognito user pools authorizer for a REST API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) is a common implementation with a low barrier to entry. You can also evaluate the body, query string parameters, and headers of a request to this type of authorizer.
+ The ID token is valid and isn't expired. When you pass an ID token to an Amazon Cognito authorizer, you can perform additional validation of the ID token contents on your application server.
+ A group, claim, attribute, or role in an access or ID token meets the requirements that you define in a Lambda function. A [Lambda authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html) parses the token in the request header and evaluates it for an authorization decision. You can construct custom logic in your function or make an API request to [Amazon Verified Permissions](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/what-is-avp.html).

You can also authorize requests to an [AWS AppSync GraphQL API](https://docs.aws.amazon.com/appsync/latest/devguide/security-authz.html#amazon-cognito-user-pools-authorization) with tokens from a user pool.

# Accessing AWS services using an identity pool after sign-in
Accessing AWS resources using an identity pool

After your users sign in with a user pool, they can access AWS services with temporary API credentials that are issued from an identity pool.

Your web or mobile app receives tokens from a user pool. When you configure your user pool as an identity provider to your identity pool, the identity pool exchanges tokens for temporary AWS credentials. These credentials can be scoped to IAM roles and their policies that give users access to a limited set of AWS resources. For more information, see [Identity pools authentication flow](authentication-flow.md).

The following diagram shows how an application signs in with a user pool, retrieves identity pool credentials, and requests an asset from an AWS service.

![\[A flow diagram of an application that authenticates with an Amazon Cognito user pool and authorizes access to AWS resources with an identity pool.\]](http://docs.aws.amazon.com/cognito/latest/developerguide/images/access-services-identity-pool.png)


You can use identity pool credentials to:
+ Make fine-grained authorization requests to Amazon Verified Permissions with your user's own credentials.
+ Connect to an Amazon API Gateway REST API or an AWS AppSync GraphQL API that authorizes connections with IAM.
+ Connect to a database backend like Amazon DynamoDB or Amazon RDS that authorizes connections with IAM.
+ Retrieve application assets from an Amazon S3 bucket.
+ Initiate a session with an Amazon WorkSpaces virtual desktop.

Identity pools don't operate exclusively within an authenticated session with a user pool. They also accept authentication directly from third-party identity providers and can generate credentials for unauthenticated guest users.

For more information about using identity pools together with user pool groups to control access to your AWS resources, see [Adding groups to a user pool](cognito-user-pools-user-groups.md) and [Using role-based access control](role-based-access-control.md). Also, for more information about identity pools and AWS Identity and Access Management, see [Identity pools authentication flow](authentication-flow.md).

## Setting up a user pool with the AWS Management Console


Create an Amazon Cognito user pool and make a note of the **User Pool ID** and **App Client ID** for each of your client apps. For more information about creating user pools, see [Getting started with user pools](getting-started-user-pools.md).

## Setting up an identity pool with the AWS Management Console


The following procedure describes how to use the AWS Management Console to integrate an identity pool with one or more user pools and client apps.

**To add an Amazon Cognito user pools identity provider (IdP)**

1. Choose **Identity pools** from the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). Select an identity pool.

1. Choose the **User access** tab.

1. Select **Add identity provider**.

1. Choose **Amazon Cognito user pool**.

1. Enter a **User pool ID** and an **App client ID**.

1. To set the role that Amazon Cognito requests when it issues credentials to users who have authenticated with this provider, configure **Role settings**.

   1. You can give users from that IdP the **Default role** that you set up when you configured your **Authenticated role**, or you can **Choose role with rules**. With an Amazon Cognito user pool IdP, you can also **Choose role with preferred\$1role claim in tokens**. For more information about the `cognito:preferred_role` claim, see [Assigning precedence values to groups](cognito-user-pools-user-groups.md#assigning-precedence-values-to-groups).

      1. If you chose **Choose role with rules**, enter the source **Claim** from your user's authentication, the **Operator** that you want to use to compare the claim to the rule, the **Value** that will cause a match to this role choice, and the **Role** that you want to assign when the **Role assignment** matches. Select **Add another** to create an additional rule based on a different condition.

      1. If you chose **Choose role with preferred\$1role claim in tokens**, Amazon Cognito issues credentials for the role in your user's `cognito:preferred_role` claim. If no preferred role claim is present, Amazon Cognito issues credentials based on your **Role resolution**.

   1. Choose a **Role resolution**. When your user's claims don't match your rules, you can deny credentials or issue credentials for your **Authenticated role**.

1. To change the principal tags that Amazon Cognito assigns when it issues credentials to users who have authenticated with this provider, configure **Attributes for access control**.
   + To apply no principal tags, choose **Inactive**.
   + To apply principal tags based on `sub` and `aud` claims, choose **Use default mappings**.
   + To create your own custom schema of attributes to principal tags, choose **Use custom mappings**. Then enter a **Tag key** that you want to source from each **Claim** that you want to represent in a tag.

1. Select **Save changes**.

## Integrating a user pool with an identity pool


After your app user is authenticated, add that user's identity token to the logins map in the credentials provider. The provider name will depend on your Amazon Cognito user pool ID. It will have the following structure:

```
cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>
```

You can derive the value for *<region>* from the **User Pool ID**. For example, if the user pool ID is `us-east-1_EXAMPLE1`, then the *<region>* is `us-east-1`. If the user pool ID is `us-west-2_EXAMPLE2`, then the *<region>* is `us-west-2`.

------
#### [ JavaScript ]

```
var cognitoUser = userPool.getCurrentUser();

if (cognitoUser != null) {
	cognitoUser.getSession(function(err, result) {
		if (result) {
			console.log('You are now logged in.');

			// Add the User's Id Token to the Cognito credentials login map.
			AWS.config.credentials = new AWS.CognitoIdentityCredentials({
				IdentityPoolId: 'YOUR_IDENTITY_POOL_ID',
				Logins: {
					'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>': result.getIdToken().getJwtToken()
				}
			});
		}
	});
}
```

------
#### [ Android ]

```
cognitoUser.getSessionInBackground(new AuthenticationHandler() {
	@Override
	public void onSuccess(CognitoUserSession session) {
		String idToken = session.getIdToken().getJWTToken();

		Map<String, String> logins = new HashMap<String, String>();
		logins.put("cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>", session.getIdToken().getJWTToken());
		credentialsProvider.setLogins(logins);
	}

});
```

------
#### [ iOS - objective-C ]

```
AWSServiceConfiguration *serviceConfiguration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:nil];
AWSCognitoIdentityUserPoolConfiguration *userPoolConfiguration = [[AWSCognitoIdentityUserPoolConfiguration alloc] initWithClientId:@"YOUR_CLIENT_ID"  clientSecret:@"YOUR_CLIENT_SECRET" poolId:@"YOUR_USER_POOL_ID"];
[AWSCognitoIdentityUserPool registerCognitoIdentityUserPoolWithConfiguration:serviceConfiguration userPoolConfiguration:userPoolConfiguration forKey:@"UserPool"];
AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:@"UserPool"];
AWSCognitoCredentialsProvider *credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1 identityPoolId:@"YOUR_IDENTITY_POOL_ID" identityProviderManager:pool];
```

------
#### [ iOS - swift ]

```
let serviceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)
let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", poolId: "YOUR_USER_POOL_ID")
AWSCognitoIdentityUserPool.registerCognitoIdentityUserPoolWithConfiguration(serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: "UserPool")
let pool = AWSCognitoIdentityUserPool(forKey: "UserPool")
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YOUR_IDENTITY_POOL_ID", identityProviderManager:pool)
```

------