Chapter 10
Amazon Cognito

WHAT'S IN THIS CHAPTER

  • Introduction to the basic concepts of Amazon Cognito
  • Learn to create a user pool
  • Learn to create an identity pool
  • Learn when to use user pools and identity pools

Amazon Cognito is Amazon's cloud-based, OAuth 2.0–compliant identity management solution. You can use Amazon Cognito to manage a database of users, allow external web and mobile applications to authenticate users against this database, and authorize access to external APIs and AWS resources.

Amazon Cognito consists of two different components:

  • Amazon Cognito user pools
  • Amazon Cognito identity pools

In this chapter you will learn about these components and how to use them together to provide secure access to your AWS resources.

Key Concepts

In this section, you learn some of the key concepts you will encounter when working with Amazon Cognito.

Authentication

Authentication refers to the concept of determining who a user is. This can be achieved in various ways, but the most common method is to ask a user for a username and password and compare the values provided by the user against a user database. The user database contains not just the username and password, but also other attributes such as a phone number and email address.

Authorization

Authorization refers to the concept of determining what systems an authenticated user can access, and what actions they can take on the system.

Identity Provider

An identity provider is a RESTful API service that is compliant with a well-known standard such as OAuth 2.0, OpenID Connect (OIDC), or SAML, and either includes a user database or is integrated with an external user database. Identity providers allow users to provide their credentials (such as username and password). The identity provider validates these credentials against a database, and issues a token that stands as proof of authentication.

Client

In the context of an authentication flow, a client is an external (third-party) application that your users want to use to access their information, which is held in your systems. The client application can also be your own application, in which case the authentication flow can be simplified.

OAuth 2.0

OAuth 2.0 is an authorization framework that allows external client applications to obtain limited access to a user's resources, on behalf of the user, without the user having to divulge their credentials to the client application. Here is the formal definition of OAuth 2.0 from the Internet Engineering Task Force in RFC 6749 (IETF: https://tools.ietf.org/html/rfc6749):

The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.

Depending on the capabilities of the client application, and the level of trust the user is willing to place in the client application, OAuth 2.0 defines four different types of flows (also known as grant types):

  • Authorization Code Grant
  • Implicit Grant
  • Resource Owner Password Credentials Grant
  • Client Credentials Grant

OpenID Connect

OpenID Connect is an authentication protocol, built on top of OAuth 2.0. OAuth 2.0 is a loosely defined authorization framework; it does not define details such as the technical format of the access token, or how the access token can be verified by the server. OIDC builds upon these shortcomings and adds the concept of a Jason Web Token (JWT)-based identity token on top of the access token. The attributes of the identity token are referred to as claims and are defined in RFC 7519.

Amazon Cognito User Pool

An Amazon Cognito user pool is a database of users and a set of services that allow creating user records into the database (sign up) and authenticating users against this database. Unlike IAM users, users in an Amazon Cognito user pool cannot log in to the AWS management console or access AWS services such as Amazon S3, AWS Lambda, and so on.

Each user in a user pool has a set of configurable attributes associated with a user record such as name, email address, and phone number, some of which are optional. Amazon Cognito user pools provide the necessary server-side APIs to create users in a user pool, provide security features such as multifactor authentication and email verification, and also allow you to invoke AWS Lambda functions at different points of the user registration and authentication process.

Amazon Cognito user pools are fully OAuth 2.0–compliant and support the Auth Code, Implicit, and Client Credentials flows. The result of authentication against an Amazon Cognito user pool is an access token and a signed JWT identity token. The access token can be used with any REST API that is designed to accept bearer access tokens, and the identity token can be used by a REST API to get additional information on the authenticated user (such as address, phone number, and so on). The additional user information available in the identity token is expressed as a set of JWT claims.

The identity token can also be used with an Amazon Cognito identity pool to obtain a temporary set of credentials that can be used to access AWS services such as S3 and DynamoDB. Amazon Cognito signs the identity token, and the signature of the token can be validated against a well-known certificate that Amazon publishes on the Internet.

Identity Pool

An identity pool is a collection of Amazon Cognito federated identity objects, which are associated with authenticated users. A federated identity object consists of a set of credentials that can be used to access services such as Amazon S3 and Amazon DynamoDB. A federated identity object is short-lived, and only issued to a requesting party that can provide a valid OIDC-compliant identity token or SAML token. Each federated identity object has an IAM policy document that controls what AWS resources can be accessed.

Amazon Cognito Federated Identities

Amazon Cognito Federated Identities is a service that provides the mechanism to exchange a valid OIDC-compliant identity token or SAML token for a federated identity object. If you are using Amazon Cognito user pools as your OAuth 2.0 identity provider, you can easily integrate the user pool with an identity pool to seamlessly exchange the JWT identity token you receive from the user pool for a federated identity object.

User pools and identity pools are used together to form a complete authentication and authorization solution to allow access to your AWS resources to non-IAM users using your web or mobile apps.

Besides Amazon Cognito user pools, identity pools can be used to provide temporary AWS credentials for users who have authenticated with the following additional mechanisms:

  • Facebook login
  • Google login
  • Amazon login
  • Other OIDC providers such as Auth0, Ping, etc.
  • SAML providers

Common Tasks

In this section, you learn to use the Amazon Cognito management console to create S3 user pools and identity pools, and configure identity pools to issue federated identities for users who present a valid access token issued by an Amazon Cognito user pool. Log in to the IAM console using your dedicated IAM user-specific sign-in link and navigate to the Amazon Cognito service home page (Figure 10.1).

Screenshot of accessing the S3 management console.

FIGURE 10.1 Accessing the S3 management console

Creating a User Pool

To create a new Amazon Cognito user pool, follow these steps.

  1. Click the Manage User Pools button on the Cognito splash screen to access a list of existing user pools (Figure 10.2).
    Screenshot of Amazon Cognito splash screen.
    FIGURE 10.2 Amazon Cognito splash screen
  2. To add a new user pool, click the Create A User Pool button on the top-right corner of the screen (Figure 10.3). User pools are specific to AWS regions. Make sure you have set up the AWS management console to use the correct region before creating the user pool.
    Screenshot of creating a new user pool.
    FIGURE 10.3 Creating a new user pool
  3. Type a name for the new user pool and click the Step Through Settings button (Figure 10.4). The user pool name must be between 1 and 128 characters long and cannot be changed after the user pool is created. Pool names can contain uppercase and lowercase letters (a–z, A–Z), numbers (0–9), and the following special characters: + = , . @ and -.
    Screenshot of specifying the name of the new user pool.
    FIGURE 10.4 Specifying the name of the new user pool
  4. The Attributes screen allows you to specify how you want users to sign in, and what information they need to provide during the sign-up process. You can configure a user pool to require users to set up a unique username to identify themselves, which is different from their email address, or allow users to use their email address/phone number as the username.

    During the sign-up process, a profile is generated for the user. At the very least, the profile will consist of the username and the password, but it can also contain other attributes such as birthdate and address. Select the attributes that you require from users when they sign up for your app (Figure 10.5).

    Screenshot of user pool attributes.

    FIGURE 10.5 User pool attributes

    Attributes can be thought of as fields in a table that contain information on registered users. Every user can have one or more of the following standard attributes:

    • address
    • birthdate
    • email_address
    • family_name
    • gender
    • given_name
    • locale
    • middle_name
    • name
    • nickname
    • phone_number
    • picture
    • preferred_username
    • profile
    • timezone
    • updated_at
    • website

    Most of these attributes are optional. Place checkmarks next to attributes that you want to make mandatory. Attributes cannot be switched between required and nonrequired once you create the user pool. When a user is authenticated against a user pool, the JWT identity token that is returned by Amazon Cognito can contain these attributes as claims.

    In case you are wondering, the attribute names available to choose from while creating a username are standard attribute names, as described in the OpenID Connect specification available at http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims.

    If you need additional attributes beyond those available in the standard list, you can create custom attributes on the same screen (Figure 10.6).

    Screenshot of adding a custom attribute to a user pool.

    FIGURE 10.6 Adding a custom attribute to a user pool

    Click the Next Step button when you are ready to proceed.

  5. The Policies screen allows you to set a password security policy, set up whether users can sign up without the help of an administrator, and indicate the number of days until an unused administrator-created account expires.

    Using the options on the screen, select the security requirements that you want passwords to adhere to (Figure 10.7).

    Screenshot of setting up user pool policies.

    FIGURE 10.7 Setting up user pool policies

    Ensure the Allow Users To Sign Themselves Up option is selected. If it is not, users cannot sign up using your app; you have to manually create accounts for them in the user pool using the Amazon Cognito management console. You can also specify the number of days that must elapse before any unused user accounts that were created through the management console expire. The default value is 7 days.

    Click the Next Step button to proceed.

  6. The MFA and Verifications screen allows you to enable multi-factor authentication and email/phone number verification for user accounts (Figure 10.8).
    Screenshot of multifactor authentication settings for the user pool.

    FIGURE 10.8 Multifactor authentication settings for the user pool

    When enabled, MFA adds an additional security step when someone attempts to log in to your mobile app. In this additional step, the individual is asked to provide a temporary and unique six-digit numeric code that an authentication device generates.

    You can also select whether users need to verify their email address or phone number as part of the sign-up process. If you disable both email address and phone number verification, users are unable to reset forgotten passwords.

    If you decide to enable phone number verification, Cognito needs to use Amazon SNS to send SMS messages to a user's devices. For Cognito to be able to access Amazon SNS, you are prompted to create a new IAM role that can be assumed by Cognito when communicating with Amazon SNS.

  7. The Message Customizations screen allows you to customize the text of the email and SMS verification message (Figure 10.9).
    Screenshot of customizing email and SMS verification messages.

    FIGURE 10.9 Customizing email and SMS verification messages

    You do not need to change the default messages. However, if you do choose to do so, ensure that your messages contain the {####} placeholder string. Cognito replaces the placeholder string with a four-digit verification code that the user must enter into your app as part of the sign-up process.

    Click the Next Step button to proceed.

  8. The Tags screen allows you to add cost allocation tags that can be used to track your AWS costs (Figure 10.10).
    Screenshot of cost allocation tag setup screen.

    FIGURE 10.10 Cost allocation tag setup screen

    If you add cost allocation tags to a user pool, your AWS cost allocation report includes costs and usage aggregated using these tags. If you would like to learn more about using cost allocation tags with your AWS resources, visit http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html.

    Click the Next Step button to proceed.

  9. The Devices screen gives you options to decide if you would like the user pool to remember the devices used by your users to log in to your app (Figure 10.11).
    Screenshot of setting up a user pool to remember devices.

    FIGURE 10.11 You can set up a user pool to remember devices

    You can choose between three options:

    • No: This is the default option. Devices are not remembered.
    • Always: Every device used by users of your app is remembered.
    • User Opt In: Your users are given an option to remember the device that they are using. You must create the user interface in your app to allow the user to opt in.

    If you choose to have Cognito remember a user's devices, a device identifier (key and secret) is assigned to each device the first time a user signs in with that device. This key is not used for anything other than identifying the device, but Cognito tracks it. You also have the option of suppressing MFA challenges for devices that Cognito tracks.

    Click the Next Step button to proceed.

  10. The App Clients screen allows you to configure external applications that can connect to the user pool to authenticate users (Figure 10.12). Each application defined in this screen is issued a client ID, and sometimes a client secret. You will need to provide these values to the app developer. The client secret should not be shared publicly, and the external application must have a secure mechanism to store this client secret.
    Screenshot of configuring applications that can use the user pool to authenticate users.

    FIGURE 10.12 Configuring applications that can use the user pool to authenticate users

    In the case of mobile and web applications that have access to a trusted server, a common practice is to have the application retrieve the client secret from its own trusted server before connecting to Amazon Cognito to authenticate the user. If the application is not capable of storing the client secret securely (such as a JavaScript application), you need to ensure that you do not generate a client secret while configuring the app entry in the user pool.

    You can add apps to the user pool after it has been created, in which case you can skip to the next step. If you would like to add an application at this stage, click the Add An App Client link on the page, and remember to uncheck the Generate Client Secret option if the app is unable to secure the client secret (Figure 10.13).

    Screenshot of creating application screen.

    FIGURE 10.13 Create Application screen

    While creating the application, you can also choose which of the user pool attributes will be present as claims in the JWT identity token that is generated after the user successfully authenticates. Click the Create App Client button under the fields to finish creating the app. Your new app is listed (Figure 10.14), and you have the option to create additional apps within the user pool.

    Screenshot of a list of client applications in the user pool.

    FIGURE 10.14 List of client applications in the user pool

    If you are creating the app client entry during the process of creating the user pool, the client ID and client secret will not be available to view until after the pool has been created.

    Click the Triggers menu on the left-side menu to proceed to the next step.

  11. The Triggers screen lets you associate AWS Lambda functions with specific user pool triggers (Figure 10.15).
    Screenshot of use triggers to call AWS Lambda functions at specific points in the user authentication process.

    FIGURE 10.15 Use triggers to call AWS Lambda functions at specific points in the user authentication process.

    As of when this book was written, the following triggers are available:

    • Pre Sign-Up: Invoked when users submit all their details to create a new account in the user pool. Your AWS Lambda function can validate the information submitted by the user and accept or decline the sign-up request.
    • Pre Authentication: Invoked when users submit their details to authenticate against the user pool. Your AWS Lambda function can validate the information submitted by the user and accept or decline the authentication request.
    • Post Authentication: Invoked after a user is authenticated. Your AWS Lambda function can be used to generate appropriate analytic messages or send an email message to the user's account.
    • Custom Message: Invoked before an email/SMS verification message is sent and before an MFA message is sent. Your AWS Lambda function can customize the content of the message that is sent.
    • Post Confirmation: Invoked after the user has successfully completed email/SMS verification. Your AWS Lambda function can be used to generate appropriate analytic messages or send an email message to the user's account.
    • Define Auth Challenge: Invoked at the start of a custom authentication flow. Your AWS Lambda function can define the authentication challenge that the user will need to satisfy as part of the custom authentication flow.
    • Create Auth Challenge: Invoked after a custom authentication flow has begun. Your AWS Lambda function is called to create the challenge that was defined in the AWS Lambda function executed for the Define Auth Challenge trigger.
    • Verify Auth Challenge Response: Invoked to verify the validity of the user's response to a custom authentication challenge.
    • Pre Token Generation: Invoked before the JWT identity token is generated. Your AWS Lambda function can customize the claims in the JWT token.
    • User Migration: Invoked when users are migrated from an existing directory service to your user pool.
  12. The Review screen allows you to review the options you have specified so far (Figure 10.16).
    Screenshot of User pool Review screen.

    FIGURE 10.16 User pool Review screen

    When you have finished reviewing the settings for the user pool, click the Create Pool button to create the user pool.

Retrieving the App Client Secret

While configuring the list of client apps that have access to unauthenticated APIs in the user pool, you have the option of generating a client ID and a client secret for each app. The client secret is only available after the user pool has been created.

Once you have finished creating the user pool, your new user pool is listed alongside any existing user pools in the Cognito user pool management console.

Click your user pool and navigate to the App Clients section of the user pool to view a list of app clients. Click the Show Details button to view the client ID and client secret (Figure 10.17).

Screenshot of Click the Show Details button to reveal the app client ID and the app client secret.

FIGURE 10.17 Click the Show Details button to reveal the app client ID and the app client secret.

It is your responsibility to safely distribute and store the client secret within your application.

Creating an Identity Pool

An identity pool is a database of federated identities that can be used to obtain a set of temporary credentials to access other AWS services such as S3 and DynamoDB. These federated identities are unique within an identity pool and are linked to identities from identity providers such as Amazon Cognito user pools, Facebook, Google, and Amazon.com.

Identity pools are specific to AWS regions. Make sure you have set up the AWS management console to use the correct region before creating the identity pool. To create a new Amazon Cognito identity pool, follow these steps:

  1. Click the Manage Identity Pools button on the Cognito splash screen (Figure 10.18).
    Screenshot of Amazon Cognito splash screen.
    FIGURE 10.18 Amazon Cognito splash screen
  2. If you do not have any identity pools in the AWS region, you will be taken to the first step of the Create Identity Pool wizard (Figure 10.19).
    Screenshot of creating a new identity pool.

    FIGURE 10.19 Creating a new identity pool

    If you have one or more existing identity pools in the AWS region, you will be taken to a screen that lists the identity pools. Locate the Create New Identity Pool button in the top-left corner of the screen (Figure 10.20).

    Screenshot of a list of existing identity pools.

    FIGURE 10.20 List of existing identity pools

  3. Specify a name for your identity pool. It is a good idea to uncheck the Enable Access To Unauthenticated Identities check box. Enabling this check box will generate a set of AWS credentials for users who have not authenticated with an identity provider.

    One scenario where you may want to enable access through unauthenticated identities is if the external application is your own, and your app is built in such a way that users do not have to authenticate on the first screen of the app. In such a case, your app may need to access some of your AWS resources to provide the functionality that is not dependent on knowing who is using the app. For example, a recent announcements screen in your app could be powered by an Amazon DynamoDB table in your AWS account. For your app to read items from this Amazon DynamoDB table, it would have to use the set of unauthenticated credentials.

  4. Expand the Authentication Provider's section of the page and configure the identity providers whose identity tokens you wish to accept. If you are using Amazon Cognito user pools as your identity provider, enter the user pool ID and the app client ID (Figure 10.21).
    Screenshot of specifying the Amazon Cognito user pool ID and app client ID.

    FIGURE 10.21 Specifying the Amazon Cognito user pool ID and app client ID

    If you have multiple app clients defined in your user pool, you will need to create multiple identity pools, as an identity pool can only be linked to a single app client in your user pool.

    Click the Create Pool button at the bottom of the page to proceed.

  5. The next screen lets you create new roles for authenticated and unauthenticated identities (Figure 10.22). You also have the option to select an existing role.
    Screenshot of Cognito, by default, creates new roles for authenticated and unauthenticated identities.

    FIGURE 10.22 Cognito, by default, creates new roles for authenticated and unauthenticated identities.

    The authenticated role decides what services from your account can be accessed by an external application provided the user of the app has successfully authenticated with an identity provider. The unauthenticated role controls what services can be accessed by an external app without an authenticated user. The app will need to provide a set of credentials to prove it is a trusted application, even though the user who is using the app is unauthenticated.

    You can update the policies using the IAM management console to exercise fine-grained control over your AWS resources.

  6. Click the Allow button at the bottom of the screen to finish creating the new identity pool.

User Pools or Identity Pools: Which One Should You Use?

If you are new to Amazon Cognito, and API authentication in general, it can be difficult to understand the differences between user pools and identity pools and when to use what.

Underneath the hood, AWS is a set of REST web services; however, not all of these web services accept OIDC access and identity tokens. In fact, the only web service that directly supports OIDC tokens is Amazon API Gateway. What this means is that you cannot access your Amazon S3 resources using OIDC tokens unless you expose the Amazon S3 resources to the outside world via an Amazon API Gateway.

The native AWS REST APIs that power services like Amazon S3, Amazon Dynamo DB, and AWS Lambda all work using a set of credentials consisting of an access key ID and a secret access key. When you create IAM users, you have the option of generating these keys (Figure 10.23).

Screenshot of accessing the credentials needed to access AWS services.

FIGURE 10.23 Accessing the credentials needed to access AWS services

When you configure the AWS CLI, you are asked to provide these credentials as part of the configuration process:

IAM allows you to issue access key IDs and secret access keys on a per-IAM user basis. You create IAM users manually using the IAM management console, and share the access key ID and secret access key with the user securely, asking the user to keep them safe. The access key ID and secret access key are bearer credentials—there is no way for the AWS CLI to know that the person typing those values is not the user for whom they were created—which is why you ask your IAM users to keep these values safe and never include them in your apps.

An Amazon Cognito identity pool issues temporary access key IDs and secret access keys and, therefore, identity pools should be used only when you want to access your AWS resources, without using an API gateway. But the question is, who should the identity pool issue these keys to? This is where linking the identity pool to an identity provider comes in. Once an identity pool is linked to an identity provider, temporary AWS credentials will only be issued to those requests that present a signed identity token issued by the identity provider.

An Amazon Cognito user pool is an identity provider much like Auth0 or Ping. It allows users to authenticate themselves and receive an access token and an identity token. These tokens can be used with any REST API that can accept OIDC tokens. Therefore, if you need to access some existing, non-AWS, REST APIs that can accept OIDC tokens, then you should only use Amazon Cognito user pools.

Summary

  • Amazon Cognito is Amazon's cloud-based, OAuth 2.0-compliant identity management solution.
  • An Amazon Cognito user pool is a database of users and a set of services that allow creating user records into the database (sign-up) and authenticating users against this database.
  • Amazon Cognito user pools are fully OAuth 2.0–compliant and support the Auth Code, Implicit, and Client Credentials flows.
  • An identity pool is a collection of Amazon Cognito federated identity objects, which are associated with authenticated users.
  • A federated identity object consists of a set of credentials that can be used to access AWS services such as Amazon S3 and Amazon DynamoDB.
  • User pools and identity pools are used together to form a complete authentication and authorization solution to allow access to your AWS resources to non-IAM users using your web or mobile apps.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.246