

# User pool endpoints and managed login reference
<a name="cognito-userpools-server-contract-reference"></a>

Amazon Cognito has two models of user pool authentication: with the user pools API and with the OAuth 2.0 authorization server. Use the API when you want to retrieve OpenID Connect (OIDC) tokens with an AWS SDK in your application back end. Use the authorization server when you want to implement your user pool as an OIDC provider. The authorization server adds features like [federated sign-in](cognito-user-pools-identity-federation.md), [API and M2M authorization with access token scopes](cognito-user-pools-define-resource-servers.md), and [managed login](cognito-user-pools-managed-login.md). You can use the API and OIDC models each on their own or together, configured at the user pool level or at the [app client](user-pool-settings-client-apps.md) level. This section is a reference for the implementation of the OIDC model. For more information about the two authentication models, see [Understanding API, OIDC, and managed login pages authentication](authentication-flows-public-server-side.md#user-pools-API-operations).

Amazon Cognito activates the public webpages listed here when you assign a domain to your user pool. Your domain serves as a central access point for all of your app clients. They include managed login, where your users can sign up and sign in ([Login endpoint](login-endpoint.md)), and sign out ([Logout endpoint](logout-endpoint.md)). For more information about these resources, see [User pool managed login](cognito-user-pools-managed-login.md).

These pages also include the public web resources that allow your user pool to communicate with third-party SAML, OpenID Connect (OIDC) and OAuth 2.0 identity providers (IdPs). To sign in a user with a federated identity provider, your users must initiate a request to the interactive managed login [Login endpoint](login-endpoint.md) or the OIDC [Authorize endpoint](authorization-endpoint.md). The Authorize endpoint redirects your users either to your managed login pages or your IdP sign-in page.

Your app can also sign in *local users* with the [Amazon Cognito user pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/Welcome.html). A local user exists exclusively in your user pool directory without federation through an external IdP.

In addition to managed login, Amazon Cognito integrates with SDKs for Android, iOS, JavaScript, and more. The SDKs provide tools to perform user pool API operations with Amazon Cognito API service endpoints. For more information about service endpoints, see [Amazon Cognito Identity endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/cognito_identity.html).

**Warning**  
Don't pin the end-entity or intermediate Transport Layer Security (TLS) certificates for Amazon Cognito domains. AWS manages all certificates for all of your user pool endpoints and prefix domains. The certificate authorities (CAs) in the chain of trust that supports Amazon Cognito certificates dynamically rotate and renew. When you pin your app to an intermediate or leaf certificate, your app can fail without notice when AWS rotates certificates.  
Instead, pin your application to all available [Amazon root certificates](https://www.amazontrust.com/repository/). For more information, see best practices and recommendations at [Certificate pinning](https://docs.aws.amazon.com/acm/latest/userguide/acm-bestpractices.html#best-practices-pinning) in the *AWS Certificate Manager User Guide*.

**Topics**
+ [User-interactive managed login and classic hosted UI endpoints](managed-login-endpoints.md)
+ [Identity provider and relying party endpoints](federation-endpoints.md)
+ [OAuth 2.0 grants](federation-endpoints-oauth-grants.md)
+ [Using PKCE in authorization code grants](using-pkce-in-authorization-code.md)
+ [Managed login and federation error responses](federation-endpoint-idp-responses.md)

# User-interactive managed login and classic hosted UI endpoints
<a name="managed-login-endpoints"></a>

Amazon Cognito activates the managed login endpoints in this section when you add a domain to your user pool. They are webpages where your users can complete the core authentication operations of a user pool. They include pages for password management, multi-factor authentication (MFA), and attribute verification.

The webpages that make up managed login are a front-end web application for interactive user sessions with your customers. Your app must invoke managed login in your users' browsers. Amazon Cognito doesn't support programmatic access to the webpages in this chapter. Those federation endpoints in the [Identity provider and relying party endpoints](federation-endpoints.md) that return a JSON response can be queried directly in your app code. The [Authorize endpoint](authorization-endpoint.md) redirects either to managed login or to an IdP sign-in page and also must be opened in users' browsers.

All user pool endpoints accept traffic from IPv4 and IPv6 source IP addresses.

The topics in this guide describe frequently-used managed login and classic hosted UI endpoints in detail. The difference between managed login and the hosted UI is visible, not functional. Except for `/passkeys/add`, all paths are shared between the two versions of managed login branding.

Amazon Cognito makes the webpages that follow available when you assign a domain to your user pool.


**Managed login endpoints**  

| Endpoint URL | Description | How it's accessed | 
| --- | --- | --- | 
| https://Your user pool domain/login | Signs in user pool local and federated users. |  Redirect from endpoints like [Authorize endpoint](authorization-endpoint.md), `/logout`, and `/confirmforgotPassword`. See [Login endpoint](login-endpoint.md).  | 
| https://Your user pool domain/logout | Signs out user pool users. |  Direct link. See [Logout endpoint](logout-endpoint.md).  | 
| https://Your user pool domain/confirmUser | Confirms users who have selected an email link to verify their user account. |  User selected link in an email message.  | 
| https://Your user pool domain/signup | Signs up a new user. The /login page directs your user to /signup when they select Sign up. |  Direct link with same parameters as `/oauth2/authorize`.  | 
| https://Your user pool domain/confirm | After your user pool sends a confirmation code to a user who signed up, prompts your user for the code. |  Redirect-only from `/signup`.  | 
| https://Your user pool domain/forgotPassword | Prompts your user for their user name and sends a password-reset code. The /login page directs your user to /forgotPassword when they select Forgot your password?. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/managed-login-endpoints.html)  | 
| https://Your user pool domain/confirmforgotPassword | Prompts your user for their password-reset code and a new password. The /forgotPassword page directs your user to /confirmforgotPassword when they select Reset your password. | Redirect-only from /forgotPassword. | 
| https://Your user pool domain/resendcode | Sends a new confirmation code to a user who has signed up in your user pool. |  Redirect-only from **Send a new code** link at `/confirm`.  | 
| https://Your user pool domain/passkeys/add | Registers a new [passkey](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-passkey). Only available in managed login. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cognito/latest/developerguide/managed-login-endpoints.html)  | 

**Topics**
+ [The managed login sign-in endpoint: `/login`](login-endpoint.md)
+ [The managed login sign-out endpoint: `/logout`](logout-endpoint.md)

# The managed login sign-in endpoint: `/login`
<a name="login-endpoint"></a>

The login endpoint is an authentication server and a redirect destination from [Authorize endpoint](authorization-endpoint.md). It's the entry point to managed login when you don't specify an identity provider. When you generate a redirect to the login endpoint, it loads the login page and presents the authentication options configured for the client to the user.

**Note**  
The login endpoint is a component of managed login. In your app, invoke federation and managed login pages that redirect to the login endpoint. Direct access by users to the login endpoint isn't a best practice.

## GET /login
<a name="get-login"></a>

The `/login` endpoint only supports `HTTPS GET` for your user's initial request. Your app invokes the page in a browser like Chrome or Firefox. When you redirect to `/login` from the [Authorize endpoint](authorization-endpoint.md), it passes along all the parameters that you provided in your initial request. The login endpoint supports all the request parameters of the authorize endpoint. You can also access the login endpoint directly. As a best practice, originate all your users' sessions at `/oauth2/authorize`.

**Example – prompt the user to sign in**

This example displays the login screen.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/login?
                response_type=code&
                client_id=ad398u21ijw3s9w3939&
                redirect_uri=https://YOUR_APP/redirect_uri&
                state=STATE&
                scope=openid+profile+aws.cognito.signin.user.admin
```

**Example – response**  
The authentication server redirects to your app with the authorization code and state. The server must return the code and state in the query string parameters and not in the fragment.

```
HTTP/1.1 302 Found
                    Location: https://YOUR_APP/redirect_uri?code=AUTHORIZATION_CODE&state=STATE
```

## User-initiated sign-in request
<a name="post-login"></a>

After your user loads the `/login` endpoint, they can enter a user name and password and choose **Sign in**. When they do this, they generate an `HTTPS POST` request with the same header request parameters as the `GET` request, and a request body with their username, password, and a device fingerprint.

# The managed login sign-out endpoint: `/logout`
<a name="logout-endpoint"></a>

The `/logout` endpoint is a redirection endpoint. It signs out the user and redirects either to an authorized sign-out URL for your app client, or to the `/login` endpoint. The available parameters in a GET request to the `/logout` endpoint are tailored to Amazon Cognito managed login use cases.

The logout endpoint is a front-end web application for interactive user sessions with your customers. Your app must invoke this and other managed login endpoints in your users' browsers.

To redirect your user to managed login to sign in again, add a `redirect_uri` parameter to your request. A `logout` request with a `redirect_uri` parameter must also include parameters for your subsequent request to the [Login endpoint](login-endpoint.md), like `client_id`, `response_type`, and `scope`.

To redirect your user to a page that you choose, add **Allowed sign-out URLs** to your app client. In your users' requests to the `logout` endpoint, add `logout_uri` and `client_id` parameters. If the value of `logout_uri` is one of the **Allowed sign-out URLs** for your app client, Amazon Cognito redirects users to that URL.

With single logout (SLO) for SAML 2.0 IdPs, Amazon Cognito first redirects your user to the SLO endpoint you defined in your IdP configuration. After your IdP redirects your user back to `saml2/logout`, Amazon Cognito responds with one more redirect to the `redirect_uri` or `logout_uri` from your request. For more information, see [Signing out SAML users with single sign-out](cognito-user-pools-saml-idp-sign-out.md).

The logout endpoint doesn't sign users out of OIDC or social identity providers (IdPs). To sign users out from their session with an external IdP, direct them to the sign-out page for that provider.

## GET /logout
<a name="get-logout"></a>

The `/logout` endpoint only supports `HTTPS GET`. The user pool client typically makes this request through the system browser. The browser is typically Custom Chrome Tab in Android or Safari View Control in iOS.

### Request parameters
<a name="get-logout-request-parameters"></a>

*client\$1id*  
The app client ID for your app. To get an app client ID, you must register the app in the user pool. For more information, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).  
Required.

*logout\$1uri*  
Redirect your user to a custom sign-out page with a *logout\$1uri* parameter. Set its value to the app client **sign-out URL** where you want to redirect your user after they sign out. Use *logout\$1uri* only with a *client\$1id* parameter. For more information, see [Application-specific settings with app clients](user-pool-settings-client-apps.md).  
You can also use the *logout\$1uri* parameter to redirect your user to the sign-in page for another app client. Set the sign-in page for the other app client as an **Allowed callback URL** in your app client. In your request to the `/logout` endpoint, set the value of the *logout\$1uri* parameter to the URL-encoded sign-in page.  
Amazon Cognito requires either a *logout\$1uri* or a *redirect\$1uri* parameter in your request to the `/logout` endpoint. A *logout\$1uri* parameter redirects your user to another website. If both *logout\$1uri* and *redirect\$1uri* parameters are included in your request to the `/logout` endpoint, Amazon Cognito will utilize the *logout\$1uri* parameter exclusively, overriding the *redirect\$1uri* parameter.

*`nonce`*  
(Optional) A random value that you can add to the request. The nonce value that you provide is included in the ID token that Amazon Cognito issues. To guard against replay attacks, your app can inspect the `nonce` claim in the ID token and compare it to the one you generated. For more information about the `nonce` claim, see [ID token validation](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation) in the *OpenID Connect standard*.

**redirect\$1uri**  
Redirect your user to your sign-in page to authenticate with a *redirect\$1uri* parameter. Set its value to the app client **Allowed callback URL** where you want to redirect your user after they sign in again. Add *client\$1id*, *scope*, *state*, and *response\$1type* parameters that you want to pass to your `/login` endpoint.  
Amazon Cognito requires either a *logout\$1uri* or a *redirect\$1uri* parameter in your request to the `/logout` endpoint. To redirect your user to your `/login` endpoint to reauthenticate and pass tokens to your app, add a *redirect\$1uri* parameter. If both *logout\$1uri* and *redirect\$1uri* parameters are included in your request to the `/logout` endpoint, Amazon Cognito overrides the *redirect\$1uri* parameter and processes the *logout\$1uri* parameter exclusively.

*response\$1type*  
The OAuth 2.0 response that you want to receive from Amazon Cognito after your user signs in. `code` and `token` are the valid values for the *response\$1type* parameter.  
Required if you use a *redirect\$1uri* parameter.

*state*  
When your application adds a *state* parameter to a request, Amazon Cognito returns its value to your app when the `/oauth2/logout` endpoint redirects your user.  
Add this value to your requests to guard against [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) attacks.  
You can't set the value of a `state` parameter to a URL-encoded JSON string. To pass a string that matches this format in a `state` parameter, encode the string to base64, then decode it in your application.  
Strongly recommended if you use a *redirect\$1uri* parameter.

*scope*  
The OAuth 2.0 scopes that you want to request from Amazon Cognito after you sign them out with a *redirect\$1uri* parameter. Amazon Cognito redirects your user to the `/login` endpoint with the *scope* parameter in your request to the `/logout` endpoint.  
Optional if you use a *redirect\$1uri* parameter. If you don't include a *scope* parameter, Amazon Cognito redirects your user to the `/login` endpoint with a *scope* parameter. When Amazon Cognito redirects your user and automatically populates `scope`, the parameter includes all authorized scopes for your app client.

### Example requests
<a name="get-logout-request-sample"></a>

**Example – log out and redirect user to client**

Amazon Cognito redirects user sessions to the URL in the value of `logout_uri`, ignoring all other request parameters, when requests include `logout_uri` and `client_id`. This URL must be an authorized sign-out URL for the app client.

The following is an example request for sign-out and redirect to `https://www.example.com/welcome`.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/logout?
  client_id=1example23456789&
  logout_uri=https%3A%2F%2Fwww.example.com%2Fwelcome
```

**Example – log out and prompt the user to sign in as another user**

When requests omit `logout_uri` but otherwise provide the parameters that make up a well-formed request to the authorize endpoint, Amazon Cognito redirects users to managed login sign-in. The logout endpoint appends the parameters in your original request to the redirect destination.

The additional parameters that you add to the logout request must be in the list at [Request parameters](#get-logout-request-parameters). For example, the logout endpoint doesn't support automatic IdP redirect with `identity_provider` or `idp_identifier` parameters. The parameter `redirect_uri` in a request to the logout endpoint is not a sign-out URL, but a post-sign-in URL that you want to pass through to the authorize endpoint.

The following is an example request that signs a user out, redirects to the sign-in page, and provides an authorization code to `https://www.example.com` after sign-in.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/logout?
  response_type=code&
  client_id=1example23456789&
  redirect_uri=https%3A%2F%2Fwww.example.com&
  state=example-state-value&
  nonce=example-nonce-value&
  scope=openid+profile+aws.cognito.signin.user.admin
```

# Identity provider and relying party endpoints
<a name="federation-endpoints"></a>

*Federation endpoints* are user pool endpoints that serve a purpose for one of the authentication standards used by user pools. They include SAML ACS URLs, OIDC discovery endpoints, and service endpoints for user pool roles both as identity provider and relying party. Federation endpoints initiate authentication flows, receive proof of authentication from IdPs, and issue tokens to clients. They interact with IdPs, applications, and administrators, but not with users.

The full-page topics after this page have details about the OAuth 2.0 and OIDC provider endpoints that become available when you add a domain to your user pool. The following chart is a list of all federation endpoints.

Examples of [user pool domains](cognito-user-pools-assign-domain.md) are:

1. Prefix domain: `mydomain.auth.us-east-1.amazoncognito.com`

1. Custom domain: `auth.example.com`


**User pool federation endpoints**  

| Endpoint URL | Description | How it's accessed | 
| --- | --- | --- | 
| https://Your user pool domain/oauth2/authorize | Redirects a user to either managed login or to sign in with their IdP. | Invoked in customer browser to begin user authentication. See [Authorize endpoint](authorization-endpoint.md). | 
| https://Your user pool domain/oauth2/token | Returns tokens based on an authorization code or client credentials request. | Requested by app to retrieve tokens. See [Token endpoint](token-endpoint.md). | 
| https://Your user pool domain/oauth2/userInfo | Returns user attributes based on OAuth 2.0 scopes and user identity in an access token. | Requested by app to retrieve user profile. See [userInfo endpoint](userinfo-endpoint.md). | 
| https://Your user pool domain/oauth2/revoke | Revokes a refresh token and the associated access tokens. | Requested by app to revoke a token. See [Revoke endpoint](revocation-endpoint.md). | 
| https://cognito-idp.Region.amazonaws.com/your user pool ID/.well-known/openid-configuration | A directory of the OIDC architecture of your user pool.[1](#cognito-federation-oidc-discovery-note) | Requested by app to locate user pool issuer metadata. | 
| https://cognito-idp.Region.amazonaws.com/your user pool ID/.well-known/jwks.json | Public keys that you can use to validate Amazon Cognito tokens.[2](#cognito-federation-oidc-jwks-note) | Requested by app to verify JWTs. | 
| https://Your user pool domain/oauth2/idpresponse | Social identity providers must redirect your users to this endpoint with an authorization code. Amazon Cognito redeems the code for a token when it authenticates your federated user. | Redirected from OIDC IdP sign-in as the IdP client callback URL. | 
| https://Your user pool domain/saml2/idpresponse | The Assertion Consumer Response (ACS) URL for integration with SAML 2.0 identity providers. | Redirected from SAML 2.0 IdP as the ACS URL, or the origination point for IdP-initiated sign-in[3](#cognito-federation-idp-init-note). | 
| https://Your user pool domain/saml2/logout | The [Single Logout](cognito-user-pools-saml-idp-sign-out.md#cognito-user-pools-saml-idp-sign-out.title) (SLO) URL for integration with SAML 2.0 identity providers. | Redirected from SAML 2.0 IdP as the single logout (SLO) URL. Accepts POST binding only. | 

1 The `openid-configuration` document might be updated at any time with additional information that keeps the endpoint compliant with the OIDC and OAuth2 specifications.

2The `jwks.json` JSON file might be updated at any time to with new public token signing keys.

3 For more information about IdP-initiated SAML sign-in, see [Implement IdP-initiated SAML sign-in](cognito-user-pools-SAML-session-initiation.md#cognito-user-pools-SAML-session-initiation-idp-initiation).

For more information on the OpenID Connect and OAuth standards, see [OpenID Connect 1.0](http://openid.net/specs/openid-connect-core-1_0.html) and [OAuth 2.0](https://tools.ietf.org/html/rfc6749).

**Topics**
+ [The redirect and authorization endpoint](authorization-endpoint.md)
+ [The token issuer endpoint](token-endpoint.md)
+ [The user attributes endpoint](userinfo-endpoint.md)
+ [The token revocation endpoint](revocation-endpoint.md)
+ [The IdP SAML assertion endpoint](saml2-idpresponse-endpoint.md)

# The redirect and authorization endpoint
<a name="authorization-endpoint"></a>

The `/oauth2/authorize` endpoint is a redirection endpoint that supports two redirect destinations. If you include an `identity_provider` or `idp_identifier` parameter in the URL, it silently redirects your user to the sign-in page for that identity provider (IdP). Otherwise, it redirects to the [Login endpoint](login-endpoint.md) with the same URL parameters that you included in your request. 

The authorize endpoint redirects either to managed login or to an IdP sign-in page. The destination of a user session at this endpoint is a webpage that your user must interact with directly in their browser.

To use the authorize endpoint, invoke your user's browser at `/oauth2/authorize` with parameters that provide your user pool with information about the following user pool details.
+ The app client that you want to sign in to.
+ The callback URL that you want to end up at.
+ The OAuth 2.0 scopes that you want to request in your user's access token.
+ Optionally, the third-party IdP that you want to use to sign in.

You can also supply `state` and `nonce` parameters that Amazon Cognito uses to validate incoming claims.

## GET `/oauth2/authorize`
<a name="get-authorize"></a>

The `/oauth2/authorize` endpoint only supports `HTTPS GET`. Your app typically initiates this request in your user's browser. You can only make requests to the `/oauth2/authorize` endpoint over HTTPS.

You can learn more about the definition of the authorization endpoint in the OpenID Connect (OIDC) standard at [Authorization Endpoint](http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthorizationEndpoint).

### Request parameters
<a name="get-authorize-request-parameters"></a>

**`response_type`**  
Required.  
The response type. Must be `code` or `token`.   
A successful request with a `response_type` of `code` returns an authorization code grant. An authorization code grant is a `code` parameter that Amazon Cognito appends to your redirect URL. Your app can exchange the code with the [Token endpoint](token-endpoint.md) for access, ID, and refresh tokens. As a security best practice, and to receive refresh tokens for your users, use an authorization code grant in your app.  
A successful request with a `response_type` of `token` returns an implicit grant. An implicit grant is an ID and access token that Amazon Cognito appends to your redirect URL. An implicit grant is less secure because it exposes tokens and potential identifying information to users. You can deactivate support for implicit grants in the configuration of your app client.

**`client_id`**  
Required.  
The app client ID.  
The value of `client_id` must be the ID of an app client in the user pool where you make the request. Your app client must support sign-in by Amazon Cognito local users or at least one third-party IdP.

**`redirect_uri`**  
Required.  
The URL where the authentication server redirects the browser after Amazon Cognito authorizes the user.  
A redirect uniform resource identifier (URI) must have the following attributes:  
+ It must be an absolute URI.
+ You must have pre-registered the URI with a client.
+ It can't include a fragment component.
See [OAuth 2.0 - Redirection Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1.2).  
Amazon Cognito requires that your redirect URI use HTTPS, except for `http://localhost`, which you can set as a callback URL for testing purposes.  
Amazon Cognito also supports app callback URLs such as `myapp://example`.

**`state`**  
Optional, recommended.  
When your app adds a *state* parameter to a request, Amazon Cognito returns its value to your app when the `/oauth2/authorize` endpoint redirects your user.  
Add this value to your requests to guard against [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) attacks.  
You can't set the value of a `state` parameter to a URL-encoded JSON string. To pass a string that matches this format in a `state` parameter, encode the string to base64, then decode it in your app.

**`identity_provider`**  
Optional.  
Add this parameter to bypass managed login and redirect your user to a provider sign-in page. The value of the *identity\$1provider* parameter is the name of the identity provider (IdP) as it appears in your user pool.  
+ For social providers, you can use the *identity\$1provider* values `Facebook`, `Google`, `LoginWithAmazon`, and `SignInWithApple`.
+ For Amazon Cognito user pools, use the value `COGNITO`.
+ For SAML 2.0 and OpenID Connect (OIDC) identity providers (IdPs), use the name that you assigned to the IdP in your user pool.

**`idp_identifier`**  
Optional.  
Add this parameter to redirect to a provider with an alternative name for the *identity\$1provider* name. You can enter identifiers for your SAML 2.0 and OIDC IdPs from the **Social and external providers** menu of the Amazon Cognito console.

**`scope`**  
Optional.  
Can be a combination of any system-reserved scopes or custom scopes that are associated with a client. Scopes must be separated by spaces. System reserved scopes are `openid`, `email`, `phone`, `profile`, and `aws.cognito.signin.user.admin`. Any scope used must be associated with the client, or it will be ignored at runtime.  
If the client doesn't request any scopes, the authentication server uses all scopes that are associated with the client.  
An ID token is only returned if `openid` scope is requested. The access token can be only used against Amazon Cognito user pools if `aws.cognito.signin.user.admin` scope is requested. The `phone`, `email`, and `profile` scopes can only be requested if `openid` scope is also requested. These scopes dictate the claims that go inside the ID token.

**`code_challenge_method`**  
Optional.  
The hashing protocol that you used to generate the challenge. The [PKCE RFC](https://tools.ietf.org/html/rfc7636) defines two methods, S256 and plain; however, Amazon Cognito authentication server supports only S256.

**`code_challenge`**  
Optional.  
The proof of key code exchange (PKCE) challenge that you generated from the `code_verifier`. For more information, see [Using PKCE in authorization code grants](using-pkce-in-authorization-code.md).  
Required only when you specify a `code_challenge_method` parameter.

**`nonce`**  
Optional.  
A random value that you can add to the request. The nonce value that you provide is included in the ID token that Amazon Cognito issues. To guard against replay attacks, your app can inspect the `nonce` claim in the ID token and compare it to the one you generated. For more information about the `nonce` claim, see [ID token validation](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation) in the *OpenID Connect standard*.

**`lang`**  
Optional.  
The language that you want to display user-interactive pages in. Managed login pages can be localized, but hosted UI (classic) pages can't. For more information, see [Managed login localization](cognito-user-pools-managed-login.md#managed-login-localization).

**`login_hint`**  
Optional.  
A username prompt that you want to pass to the authorization server. You can collect a username, email address or phone number from your user and allow the destination provider to pre-populate the user's sign-in name. When you submit a `login_hint` parameter and no `idp_identifier` or `identity_provider` parameters to the `oauth2/authorize` endpoint, managed login fills the username field with your hint value. You can also pass this parameter to the [Login endpoint](login-endpoint.md) and automatically fill the username value.  
When your authorization request invokes a redirect to OIDC IdPs, Amazon Cognito adds a `login_hint` parameter to the request to that third-party authorizer. You can't forward login hints to SAML, Apple, Login With Amazon, Google, or Facebook (Meta) IdPs.

**`prompt`**  
Optional.  
An OIDC parameter that controls authentication behavior for existing sessions. Available in the managed login branding version only, not in the classic hosted UI. For more information from the OIDC specification, see [Authentication request](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest). The values `none` and `login` have an effect on user pool authentication behavior.  
Amazon Cognito forwards all values of `prompt` except `none` to your IdPs when users select authentication with third-party providers. This is true when the URL that users access includes an `identity_provider` or `idp_identifier` parameter, or when the authorization server redirects them to the [Login endpoint](login-endpoint.md) and they select and IdP from the available buttons.  
**Prompt parameter values**    
`prompt=none`  
Amazon Cognito silently continues authentication for users who have a valid authenticated session. With this prompt, users can silently authenticate between different app clients in your user pool. If the user is not already authenticated, the authorization server returns a `login_required` error.  
`prompt=login`  
Amazon Cognito requires users to re-authenticate even if they have an existing session. Send this value when you want to verify the user's identity again. Authenticated users who have an existing session can return to sign-in without invalidating that session. When a user who has an existing session signs in again, Amazon Cognito assigns them a new session cookie. This parameter can also be forwarded to your IdPs. IdPs that accept this parameter also request a new authentication attempt from the user.  
`prompt=select_account`  
This value has no effect on local sign-in and must be submitted in requests that redirect to IdPs. When included in your authorization request, this parameter adds `prompt=select_account` to the URL path for the IdP redirect destination. When IdPs support this parameter, they request that users select the account that they want to log in with.  
`prompt=consent`  
This value has no effect on local sign-in and must be submitted in requests that redirect to IdPs. When included in your authorization request, this parameter adds `prompt=consent` to the URL path for the IdP redirect destination. When IdPs support this parameter, they request user consent before they redirect back to your user pool. 
When you omit the `prompt` parameter from your request, managed login follows the default behavior: users must sign in unless their browser has a valid managed login session cookie. You can combine multiple values for `prompt` with a space-character delimiter, for example `prompt=login consent`.

**`resource`**  
Optional.  
The identifier of a resource that you want to bind to the access token in the `aud` claim. When you include this parameter, Amazon Cognito validates that the value is a URL and sets the audience of the resulting access token to the requested resource. You can request a user pool [resource server](cognito-user-pools-define-resource-servers.md) with an identifier in a URL format, or a URL of your choosing. Values for this parameter must begin with `https://`, `http://localhost`, or a custom URL scheme like `myapp://`.  
Resource binding is defined in [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707.html). For more information about resource servers and resource binding, see [Resource binding](cognito-user-pools-define-resource-servers.md#cognito-user-pools-resource-binding).

## Example: authorization code grant
<a name="sample-authorization-code-grant"></a>

This is an example request for an authorization code grant.

The following request initiates a session to retrieve an authorization code that your user passes to your app at the `redirect_uri` destination. This session requests scopes for user attributes and for access to Amazon Cognito self-service API operations.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=openid+profile+aws.cognito.signin.user.admin
```

The Amazon Cognito authentication server redirects back to your app with the authorization code and state. The authorization code is valid for five minutes.

```
HTTP/1.1 302 Found
Location: https://www.example.com?code=a1b2c3d4-5678-90ab-cdef-EXAMPLE11111&state=abcdefg
```

## Example: authorization code grant with PKCE
<a name="sample-authorization-code-grant-with-pkce"></a>

This example flow performs an authorization code grant with [PKCE](using-pkce-in-authorization-code.md#using-pkce-in-authorization-code.title).

This request adds a `code_challenge` parameter. To complete the exchange of a code for a token, you must include the `code_verifier` parameter in your request to the `/oauth2/token` endpoint.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=aws.cognito.signin.user.admin&
code_challenge_method=S256&
code_challenge=a1b2c3d4...
```

The authorization server redirects back to your application with the authorization code and state. Your application processes the authorization code and exchanges it for tokens.

```
HTTP/1.1 302 Found
Location: https://www.example.com?code=a1b2c3d4-5678-90ab-cdef-EXAMPLE11111&state=abcdefg
```

## Example: require re-authentication with `prompt=login`
<a name="sample-authorization-code-with-prompt-login"></a>

The following request adds a `prompt=login` parameter that requires the user to authenticate again, even if they have an existing session.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=openid+profile+aws.cognito.signin.user.admin&
prompt=login
```

The authorization server redirects to the [login endpoint](login-endpoint.md), requiring re-authentication.

```
HTTP/1.1 302 Found Location: https://mydomain.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com&state=abcdefg&scope=openid+profile+aws.cognito.signin.user.admin&prompt=login
```

## Example: silent authentication with `prompt=none`
<a name="sample-authorization-code-with-prompt-none"></a>

The following request adds a `prompt=none` parameter that silently checks if the user has a valid session.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=openid+profile+aws.cognito.signin.user.admin&
prompt=none
```

When no valid session exists, the authorization server returns an error to the redirect URI

```
HTTP/1.1 302 Found Location: https://www.example.com?error=login_required&state=abcdefg
```

When a valid session exists, the authorization server returns an authorization code.

```
HTTP/1.1 302 Found Location: https://www.example.com?code=AUTHORIZATION_CODE&state=abcdefg
```

## Example: authorization code grant with resource binding
<a name="sample-authorization-code-with-resource-binding"></a>

The following request adds a `resource` parameter to bind the access token to a specific resource server. The resulting access token creates the conditions for the target API to validate that it is the intended audience of the authenticated user's request.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=code&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=solar-system-data-api.example.com/asteroids.add&
resource=https://solar-system-data-api.example.com
```

The authorization server returns an authorization code that results in an access token with an `aud` claim of `https://solar-system-data-api.example.com`.

```
HTTP/1.1 302 Found Location: https://www.example.com?code=AUTHORIZATION_CODE&state=abcdefg
```

## Example: Token (implicit) grant without `openid` scope
<a name="sample-token-grant-without-openid-scope"></a>

This example flow generates an implicit grant and returns JWTs directly to the user's session.

The request is for an implicit grant from your authorization server. It requests scopes in the access token that authorize user profile self-service operations.

```
GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
response_type=token&
client_id=1example23456789&
redirect_uri=https://www.example.com&
state=abcdefg&
scope=aws.cognito.signin.user.admin
```

The authorization server redirects back to your application with an access token only. Because `openid` scope was not requested, Amazon Cognito doesn't return an ID token. Also, Amazon Cognito doesn't return a refresh token in this flow.

```
HTTP/1.1 302 Found
Location: https://example.com/callback#access_token=eyJra456defEXAMPLE&token_type=bearer&expires_in=3600&state=STATE
```

## Example: Token (implicit) grant with `openid` scope
<a name="sample-token-grant-with-openid-scope"></a>

This example flow generates an implicit grant and returns tokens to the user's browser.

The request is for an implicit grant from your authorization server. It requests scopes in the access token that authorize access to user attributes and self-service operations.

```
GET
https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize? 
response_type=token& 
client_id=1example23456789& 
redirect_uri=https://www.example.com& 
state=abcdefg&
scope=aws.cognito.signin.user.admin+openid+profile
```

The authorization server redirects back to your application with access token and ID token (because `openid` scope was included):

```
HTTP/1.1 302 Found
Location: https://www.example.com#id_token=eyJra67890EXAMPLE&access_token=eyJra12345EXAMPLE&token_type=bearer&expires_in=3600&state=abcdefg
```

## Examples of negative responses
<a name="get-authorize-negative"></a>

Amazon Cognito might deny your request. Negative requests come with an HTTP error code and a description that you can use to correct your request parameters. The following are examples of negative responses.
+ If `client_id` and `redirect_uri` are valid, but the request parameters aren't formatted correctly, the authentication server redirects the error to the client's `redirect_uri` and appends an error message in a URL parameter. The following are examples of incorrect formatting.
  + The request doesn't include a `response_type` parameter.
  + The authorization request provided a `code_challenge` parameter, but not a `code_challenge_method` parameter.
  + The value of the `code_challenge_method` parameter isn't `S256`.

  The following is the response to an example request with incorrect formatting.

  ```
  HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request
  ```
+ If the client requests `code` or `token` in `response_type`, but doesn't have permission for these requests, the Amazon Cognito authorization server returns `unauthorized_client` to client's `redirect_uri`, as follows:

  ```
  HTTP 1.1 302 Found Location: https://client_redirect_uri?error=unauthorized_client
  ```
+  If the client requests scope that is unknown, malformed, or not valid, the Amazon Cognito authorization server returns `invalid_scope` to the client's `redirect_uri`, as follows: 

  ```
  HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_scope
  ```
+ If there is any unexpected error in the server, the authentication server returns `server_error` to the client's `redirect_uri`. Because the HTTP 500 error doesn't get sent to the client, the error doesn't display in the user's browser. The authorization server returns the following error.

  ```
  HTTP 1.1 302 Found Location: https://client_redirect_uri?error=server_error
  ```
+ When Amazon Cognito authenticates through federation to third-party IdPs, Amazon Cognito might experience connection issues, such as the following:
  + If a connection timeout occurs while requesting token from the IdP, the authentication server redirects the error to the client’s `redirect_uri` as follows:

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=Timeout+occurred+in+calling+IdP+token+endpoint
    ```
  + If a connection timeout occurs while calling the `jwks_uri` endpoint for ID token validation, the authentication server redirects with an error to the client’s `redirect_uri` as follows:

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=error_description=Timeout+in+calling+jwks+uri
    ```
+ When authenticating by federating to third-party IdPs, the providers may return error responses. This can be due to configuration errors or other reasons, such as the following:
  + If an error response is received from other providers, the authentication server redirects the error to the client’s `redirect_uri` as follows:

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=[IdP name]+Error+-+[status code]+error getting token
    ```
  + If an error response is received from Google, the authentication server redirects the error to the client’s `redirect_uri` as follows: 

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=Google+Error+-+[status code]+[Google-provided error code]
    ```
+ When Amazon Cognito encounters an communication exception when it connects to an external IdP, the authentication server redirects with an error to the client's `redirect_uri` with either of the following messages:
  + 

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=Connection+reset
    ```
  + 

    ```
    HTTP 1.1 302 Found Location: https://client_redirect_uri?error=invalid_request&error_description=Read+timed+out
    ```

# The token issuer endpoint
<a name="token-endpoint"></a>

The OAuth 2.0 [token endpoint](https://www.rfc-editor.org/rfc/rfc6749#section-3.2) at `/oauth2/token` issues JSON web tokens (JWTs) to applications that want to complete authorization-code and client-credentials grant flows. These tokens are the end result of authentication with a user pool. They contain information about the user (ID token), the user's level of access (access token), and the user's entitlement to persist their signed-in session (refresh token). OpenID Connect (OIDC) relying-party libraries handle requests to and response payloads from this endpoint. Tokens provide verifiable proof of authentication, profile information, and a mechanism for access to back-end systems.

Your user pool OAuth 2.0 authorization server issues JSON web tokens (JWTs) from the token endpoint to the following types of sessions:

1. Users who have completed a request for an authorization code grant. Successful redemption of a code returns ID, access, and refresh tokens.

1. Machine-to-machine (M2M) sessions that have completed a client-credentials grant. Successful authorization with the client secret returns an access token.

1. Users who have previously signed in and received refresh tokens. Refresh token authentication returns new ID and access tokens.
**Note**  
Users who sign in with an authorization code grant in managed login or through federation can always refresh their tokens from the token endpoint. Users who sign in with the API operations `InitiateAuth` and `AdminInitiateAuth` can refresh their tokens with the token endpoint when [remembered devices](amazon-cognito-user-pools-device-tracking.md) is *not* active in your user pool. If remembered devices is active, refresh tokens with the [relevant API or SDK token-refresh operation](amazon-cognito-user-pools-using-the-refresh-token.md#using-the-refresh-token-api) for your app client.

The token endpoint becomes publicly available when you add a domain to your user pool. It accepts HTTP POST requests. For application security, use PKCE with your authorization code sign-in events. PKCE verifies that the user passing an authorization code is that same user who authenticated. For more information about PKCE, see [IETF RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636).

You can learn more about the user pool app clients and their grant types, client secrets, allowed scopes, and client IDs at [Application-specific settings with app clients](user-pool-settings-client-apps.md). You can learn more about M2M authorization, client credentials grants, and authorization with access token scopes at [Scopes, M2M, and resource servers](cognito-user-pools-define-resource-servers.md).

To retrieve information about a user from their access token, pass it to your [userInfo endpoint](userinfo-endpoint.md) or to a [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html) API request. The access token must contain the appropriate scopes for these requests,

## Format a POST request to the token endpoint
<a name="post-token"></a>

The `/oauth2/token` endpoint only supports `HTTPS POST`. This endpoint is not user-interactive. Handle token requests with an [OpenID Connect (OIDC) library](https://openid.net/developers/certified-openid-connect-implementations/) in your application.

The token endpoint supports `client_secret_basic` and `client_secret_post` authentication. For more information about the OIDC specification, see [Client Authentication](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication). For more information about the token endpoint from the OpenID Connect specification, see [Token Endpoint](http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint).

### Request parameters in header
<a name="post-token-request-parameters"></a>

You can pass the following parameters in the header of your request to the token endpoint.

**`Authorization`**  
If the client was issued a secret, the client can pass its `client_id` and `client_secret` in the authorization header as `client_secret_basic` HTTP authorization. You can also include the `client_id` and `client_secret` in the request body as `client_secret_post` authorization.  
The authorization header string is [Basic](https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side) `Base64Encode(client_id:client_secret)`. The following example is an authorization header for app client `djc98u3jiedmi283eu928` with client secret `abcdef01234567890`, using the Base64-encoded version of the string `djc98u3jiedmi283eu928:abcdef01234567890`:  

```
Authorization: Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw
```

**`Content-Type`**  
Set the value of this parameter to `'application/x-www-form-urlencoded'`.

### Request parameters in body
<a name="post-token-request-parameters-in-body"></a>

The following are parameters that you can request in `x-www-form-urlencoded` format in the request body to the token endpoint.

**`grant_type`**  
*Required.*  
The type of OIDC grant that you want to request.  
Must be `authorization_code` or `refresh_token` or `client_credentials`. You can request an access token for a custom scope from the token endpoint under the following conditions:  
+ You enabled the requested scope in your app client configuration.
+ You configured your app client with a client secret.
+ You enable client credentials grant in your app client.
The token endpoint returns a refresh token only when the `grant_type` is `authorization_code`.

**`client_id`**  
*Optional. Not required when you provide the app client ID in the `Authorization` header.*  
The ID of an app client in your user pool. Specify the same app client that authenticated your user.  
You must provide this parameter if the client is public and does not have a secret, or with `client_secret` in `client_secret_post` authorization.

**`client_secret`**  
*Optional. Not required when you provide the client secret in the `Authorization` header and when the app client doesn't have a secret.*  
The app client secret, if the app client has one, for `client_secret_post` authorization.

**`scope`**  
*Optional.*  
Can be a combination of any scopes that are associated with your app client. Amazon Cognito ignores scopes in the request that aren't allowed for the requested app client. If you don't provide this request parameter, the authorization server returns an access token `scope` claim with all authorization scopes that you enabled in your app client configuration. You can request any of the scopes allowed for the requested app client: standard scopes, custom scopes from resource servers, and the `aws.cognito.signin.user.admin` user self-service scope.

**`redirect_uri`**  
*Optional. Not required for client-credentials grants.*  
Must be the same `redirect_uri` that was used to get `authorization_code` in `/oauth2/authorize`.  
You must provide this parameter if `grant_type` is `authorization_code`.

**`refresh_token`**  
*Optional. Used only when the user already has a refresh token and wishes to get new ID and access tokens.*  
To generate new access and ID tokens for a user's session, set the value of `refresh_token` to a valid refresh token that the requested app client issued.  
Returns a new refresh token with new ID and access token when [refresh token rotation](amazon-cognito-user-pools-using-the-refresh-token.md#using-the-refresh-token-rotation) is active, otherwise returns only ID and access tokens. If the original access token was [bound to an API resource](cognito-user-pools-define-resource-servers.md#cognito-user-pools-resource-binding), the new access token maintains the requested API url in the `aud` claim.

**`code`**  
*Optional. Only required in authorization-code grants.*  
The authorization code from an authorization code grant. You must provide this parameter if your authorization request included a `grant_type` of `authorization_code`.

**`aws_client_metadata`**  
*Optional.*  
Information that you want to pass to the [Pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md) in [machine-to-machine (M2M)](cognito-user-pools-define-resource-servers.md) authorization flows. Your application can collect context information about the session and pass it in this parameter. When you pass `aws_client_metadata` in URL-encoded JSON format, Amazon Cognito includes it in the input event to your trigger Lambda function. Your pre token trigger event version or global Lambda trigger version must be configured for version three or later. Although Amazon Cognito accepts requests to this endpoint in authorization code and client credentials M2M flows, your user pool only passes `aws_client_metadata` to the pre token generation trigger from client credentials requests.

**`code_verifier`**  
Optional. Required only if you provided `code_challenge_method` and `code_challenge` parameters in your initial authorization request.  
The generated code verifier that your application calculated the `code_challenge` from in an authorization code grant request with [PKCE](using-pkce-in-authorization-code.md).

## Exchanging an authorization code for tokens
<a name="post-token-positive-exchanging-authorization-code-for-tokens"></a>

The following request successfully generates ID, access, and refresh tokens after authentication with an authorization-code grant. The request passes the client secret in `client_secret_basic` format in the `Authorization` header.

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token&
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=authorization_code&
client_id=1example23456789&
code=AUTHORIZATION_CODE&
redirect_uri=com.myclientapp://myclient/redirect
```

The response issues new ID, access, and refresh tokens to the user, with additional metadata.

```
HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJra1example",
    "id_token": "eyJra2example",
    "refresh_token": "eyJj3example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Client credentials with basic authorization
<a name="exchanging-client-credentials-for-an-access-token-in-request-body"></a>

The following request from an M2M application requests a client credentials grant. Because client credentials requires a client secret, the request is authorized with an `Authorization` header derived from the app client ID and secret. The request results in an access token with the two requested scopes. The request also includes client metadata that provides IP-address information and a token issued to the user who this grant is on behalf of. Amazon Cognito passes the client metadata to the pre token generation Lambda trigger.

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token >
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=client_credentials&
client_id=1example23456789&
scope=resourceServerIdentifier1%2Fscope1%20resourceServerIdentifier2%2Fscope2&
&aws_client_metadata=%7B%22onBehalfOfToken%22%3A%22eyJra789ghiEXAMPLE%22,%20%22ClientIpAddress%22%3A%22192.0.2.252%22%7D
```

Amazon Cognito passes the following input event to the pre token generation Lambda trigger.

```
{
    version: '3',
    triggerSource: 'TokenGeneration_ClientCredentials',
    region: 'us-east-1',
    userPoolId: 'us-east-1_EXAMPLE',
    userName: 'ClientCredentials',
    callerContext: {
        awsSdkVersion: 'aws-sdk-unknown-unknown',
        clientId: '1example23456789'
    },
    request: {
        userAttributes: {},
        groupConfiguration: null,
        scopes: [
           'resourceServerIdentifier1/scope1',
           'resourceServerIdentifier2/scope2'
        ],
        clientMetadata: {
            'onBehalfOfToken': 'eyJra789ghiEXAMPLE',
            'ClientIpAddress': '192.0.2.252'
        }
    },
    response: { claimsAndScopeOverrideDetails: null }
}
```

The response returns an access token. Client credentials grants are for machine-to-machine (M2M) authorization and only return access tokens.

```
HTTP/1.1 200 OK
Content-Type: application/json
{
    "access_token": "eyJra1example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Client credentials with POST body authorization
<a name="post-token-positive-exchanging-client-credentials-for-an-access-token-in-request-body"></a>

The following client-credentials grant request includes the `client_secret` parameter in the request body and doesn't include an `Authorization` header. This request uses the `client_secret_post` authorization syntax. The request results in an access token with the requested scope. The request also includes client metadata that provides IP-address information and a token issued to the user who this grant is on behalf of. Amazon Cognito passes the client metadata to the pre token generation Lambda trigger.

```
POST /oauth2/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
X-Amz-Target: AWSCognitoIdentityProviderService.Client credentials request
User-Agent: USER_AGENT
Accept: /
Accept-Encoding: gzip, deflate, br
Content-Length: 177
Referer: http://auth.example.com/oauth2/token
Host: auth.example.com
Connection: keep-alive

grant_type=client_credentials&
client_id=1example23456789&
scope=my_resource_server_identifier%2Fmy_custom_scope&
client_secret=9example87654321&
aws_client_metadata=%7B%22onBehalfOfToken%22%3A%22eyJra789ghiEXAMPLE%22,%20%22ClientIpAddress%22%3A%22192.0.2.252%22%7D
```

Amazon Cognito passes the following input event to the pre token generation Lambda trigger.

```
{
    version: '3',
    triggerSource: 'TokenGeneration_ClientCredentials',
    region: 'us-east-1',
    userPoolId: 'us-east-1_EXAMPLE',
    userName: 'ClientCredentials',
    callerContext: {
        awsSdkVersion: 'aws-sdk-unknown-unknown',
        clientId: '1example23456789'
    },
    request: {
        userAttributes: {},
        groupConfiguration: null,
        scopes: [
           'resourceServerIdentifier1/my_custom_scope'
        ],
        clientMetadata: {
            'onBehalfOfToken': 'eyJra789ghiEXAMPLE',
            'ClientIpAddress': '192.0.2.252'
        }
    },
    response: { claimsAndScopeOverrideDetails: null }
}
```

The response returns an access token. Client credentials grants are for machine-to-machine (M2M) authorization and only return access tokens.

```
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Date: Tue, 05 Dec 2023 16:11:11 GMT
x-amz-cognito-request-id: 829f4fe2-a1ee-476e-b834-5cd85c03373b

{
    "access_token": "eyJra12345EXAMPLE",
    "expires_in": 3600,
    "token_type": "Bearer"
}
```

## Authorization code grant with PKCE
<a name="post-token-positive-exchanging-authorization-code-grant-with-pkce-for-tokens"></a>

The following example request completes an authorization request that included `code_challenge_method` and `code_challenge` parameters in an authorization code grant request with [PKCE](using-pkce-in-authorization-code.md).

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=authorization_code&
client_id=1example23456789&
code=AUTHORIZATION_CODE&
code_verifier=CODE_VERIFIER&
redirect_uri=com.myclientapp://myclient/redirect
```

The response returns ID, access, and refresh tokens from the successful PKCE verification by the application.

```
HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJra1example",
    "id_token": "eyJra2example",
    "refresh_token": "eyJj3example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Token refresh without refresh token rotation
<a name="post-token-positive-exchanging-a-refresh-token-for-tokens"></a>

The following example requests provides a refresh token to an app client where [refresh token rotation](amazon-cognito-user-pools-using-the-refresh-token.md#using-the-refresh-token-rotation) is inactive. Because the app client has a client secret, the request provides an `Authorization` header.

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token >
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=refresh_token&
client_id=1example23456789&
refresh_token=eyJj3example
```

The response returns new ID and access tokens.

```
HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJra1example",
    "id_token": "eyJra2example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Token refresh with refresh token rotation
<a name="post-token-positive-refresh-token-rotation"></a>

The following example requests provides a refresh token to an app client where [refresh token rotation](amazon-cognito-user-pools-using-the-refresh-token.md#using-the-refresh-token-rotation) is active. Because the app client has a client secret, the request provides an `Authorization` header.

```
POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token >
Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZGpjOTh1M2ppZWRtaTI4M2V1OTI4OmFiY2RlZjAxMjM0NTY3ODkw

grant_type=refresh_token&
client_id=1example23456789&
refresh_token=eyJj3example
```

The response returns new ID, access, and refresh tokens.

```
HTTP/1.1 200 OK
Content-Type: application/json

{
    "access_token": "eyJra1example",
    "id_token": "eyJra2example",
    "refresh_token": "eyJj4example",
    "token_type": "Bearer",
    "expires_in": 3600
}
```

## Examples of negative responses
<a name="post-token-negative"></a>

Malformed requests generate errors from the token endpoint. The following is a general map of the response body when token requests generate an error.

```
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=UTF-8

{
"error":"invalid_request|invalid_client|invalid_grant|unauthorized_client|unsupported_grant_type"
}
```

**`invalid_request`**  
The request is missing a required parameter, includes an unsupported parameter value (other than `unsupported_grant_type`), or is otherwise malformed. For example, `grant_type` is `refresh_token` but `refresh_token` is not included. 

**`invalid_client`**  
Client authentication failed. For example, when the client includes `client_id` and `client_secret` in the authorization header, but there's no such client with that `client_id` and `client_secret`. 

**`invalid_grant`**  
Refresh token has been revoked.   
Authorization code has been consumed already or does not exist.   
App client doesn't have read access to all [attributes](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html) in the requested scope. For example, your app requests the `email` scope and your app client can read the `email` attribute, but not `email_verified`.

**`unauthorized_client`**  
Client is not allowed for code grant flow or for refreshing tokens. 

**`unsupported_grant_type`**  
Returned if `grant_type` is anything other than `authorization_code` or `refresh_token` or `client_credentials`. 

# The user attributes endpoint
<a name="userinfo-endpoint"></a>

Where OIDC issues ID tokens that contain user attributes, OAuth 2.0 implements the `/oauth2/userInfo` endpoint. An authenticated user or client receives an access token with a `scopes` claim. This claim determines the attributes that the authorization server should return. When an application presents an access token to the `userInfo` endpoint, the authorization server returns a response body that contains the user attributes that are within the boundaries set by the access token scopes. Your application can retrieve information about a user from the `userInfo` endpoint as long as it holds a valid access token with at least an `openid` scope claim.

The `userInfo` endpoint is an OpenID Connect (OIDC) [userInfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo). It responds with user attributes when service providers present access tokens that your [token endpoint](token-endpoint.md) issued. The scopes in your user's access token define the user attributes that the userInfo endpoint returns in its response. The `openid` scope must be one of the access token claims.

Amazon Cognito issues access tokens in response to user pools API requests like [https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html). Because they don't contain any scopes, the userInfo endpoint doesn't accept these access tokens. Instead, you must present access tokens from your token endpoint.

Your OAuth 2.0 third-party identity provider (IdP) also hosts a userInfo endpoint. When your user authenticates with that IdP, Amazon Cognito silently exchanges an authorization code with the IdP `token` endpoint. Your user pool passes the IdP access token to authorize retrieval of user information from the IdP `userInfo` endpoint.

The scopes in a user's access token are determined by the `scopes` request parameter in authentication requests, or the scopes that the [pre token generation Lambda trigger](user-pool-lambda-pre-token-generation.md) adds. You can decode access tokens and examine `scope` claims to see the access-control scopes that they contain. The following are some scope combinations that influence the data returned from the `userInfo` endpoint. The reserved Amazon Cognito scope `aws.cognito.signin.user.admin` has no effect on the data returned from this endpoint.Example scopes in access token and their effect on the `userInfo` response

**`openid`**  
Returns a response with all user attributes that the app client can read.

**`openid profile`**  
Returns the user attributes `name`, `family_name`, `given_name`, `middle_name`, `nickname`, `preferred_username`, `profile`, `picture`, `website`, `gender`, `birthdate`, `zoneinfo`, `locale`, and `updated_at`. Also returns [custom attributes](user-pool-settings-attributes.md#user-pool-settings-custom-attributes). In app clients that don't have read access to each attribute, the response to this scope is all of the attributes within the specification that your app client does have read access to.

**`openid email`**  
Returns basic profile information and the `email` and `email_verified` attributes.

**`openid phone`**  
Returns basic profile information and the `phone_number` and `phone_number_verified` attributes.

## GET /oauth2/userInfo
<a name="get-userinfo"></a>

Your application generates requests to this endpoint directly, not through a browser.

For more information, see [UserInfo Endpoint](http://openid.net/specs/openid-connect-core-1_0.html#UserInfo) in the OpenID Connect (OIDC) specification.

**Topics**
+ [GET /oauth2/userInfo](#get-userinfo)
+ [Request parameters in header](#get-userinfo-request-header-parameters)
+ [Example – request](#get-userinfo-positive-exchanging-authorization-code-for-userinfo-sample-request)
+ [Example – positive response](#get-userinfo-response-sample)
+ [Example negative responses](#get-userinfo-negative)

## Request parameters in header
<a name="get-userinfo-request-header-parameters"></a>

**`Authorization: Bearer <access_token>`**  
Pass the access token in the authorization header field.  
Required.

## Example – request
<a name="get-userinfo-positive-exchanging-authorization-code-for-userinfo-sample-request"></a>

```
GET /oauth2/userInfo HTTP/1.1
Content-Type: application/x-amz-json-1.1
Authorization: Bearer eyJra12345EXAMPLE
User-Agent: [User agent]
Accept: */*
Host: auth.example.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
```

## Example – positive response
<a name="get-userinfo-response-sample"></a>

```
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Content-Length: [Integer]
Date: [Timestamp]
x-amz-cognito-request-id: [UUID]
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
Server: Server
Connection: keep-alive
{
    "sub": "[UUID]",
    "email_verified": "true",
    "custom:mycustom1": "CustomValue",
    "phone_number_verified": "true",
    "phone_number": "+12065551212",
    "email": "bob@example.com",
    "username": "bob"
}
```

For a list of OIDC claims, see [Standard Claims](http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims). Currently, Amazon Cognito returns the values for `email_verified` and `phone_number_verified` as strings.

## Example negative responses
<a name="get-userinfo-negative"></a>

### Example – bad request
<a name="get-userinfo-negative-400"></a>

```
HTTP/1.1 400 Bad Request
WWW-Authenticate: error="invalid_request",
error_description="Bad OAuth2 request at UserInfo Endpoint"
```

**`invalid_request`**  
The request is missing a required parameter, it includes an unsupported parameter value, or it is otherwise malformed.

### Example – bad token
<a name="get-userinfo-negative-401"></a>

```
HTTP/1.1 401 Unauthorized
WWW-Authenticate: error="invalid_token",
error_description="Access token is expired, disabled, or deleted, or the user has globally signed out."
```

**`invalid_token`**  
The access token is expired, revoked, malformed, or it's invalid.

# The token revocation endpoint
<a name="revocation-endpoint"></a>

Users who hold a refresh token in their session have something similar to a browser cookie. They can renew their existing session as long as the refresh token is valid. Instead of prompting a user to sign in after their ID or access token expires, your application can use the refresh token to get new, valid tokens. However, you might externally determine that a user's session should be ended, or the user might elect to forget their current session. At that point, you can revoke that refresh token so that they can no longer persist their session.

The `/oauth2/revoke` endpoint revokes a user's access token that Amazon Cognito initially issued with the refresh token that you provide. This endpoint also revokes the refresh token itself and all subsequent access and identity tokens from the same refresh token. After the endpoint revokes the tokens, you can't use the revoked access tokens to access APIs that Amazon Cognito tokens authenticate.

## POST /oauth2/revoke
<a name="post-revoke"></a>

The `/oauth2/revoke` endpoint only supports `HTTPS POST`. The user pool client makes requests to this endpoint directly and not through the system browser.

### Request parameters in header
<a name="revocation-request-parameters"></a>

**`Authorization`**  
If your app client has a client secret, the application must pass its `client_id` and `client_secret` in the authorization header through Basic HTTP authorization. The secret is [Basic](https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side) `Base64Encode(client_id:client_secret)`.

**`Content-Type`**  
Must always be `'application/x-www-form-urlencoded'`.

#### Request parameters in body
<a name="revocation-request-parameters-body"></a>

**`token`**  
(Required) The refresh token that the client wants to revoke. The request also revokes all access tokens that Amazon Cognito issued with this refresh token.  
Required.

**`client_id`**  
(Optional) The app client ID for the token that you want to revoke.  
Required if the client is public and doesn't have a secret.

## Revocation request examples
<a name="revoke-sample-request"></a>

This revocation request revokes a refresh token for an app client that has no client secret. Note the `client_id` parameter in the request body.

```
POST /oauth2/revoke HTTP/1.1
Host: mydomain.auth.us-east-1.amazoncognito.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
token=2YotnFZFEjr1zCsicMWpAA&
client_id=1example23456789
```

This revocation request revokes a refresh token for an app client that *has* a client secret. Note the `Authorization` header that contains an encoded client ID and client secret, but no `client_id` in the request body.

```
POST /oauth2/revoke HTTP/1.1
Host: mydomain.auth.us-east-1.amazoncognito.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
token=2YotnFZFEjr1zCsicMWpAA
```

## Revocation error response
<a name="revoke-sample-response"></a>

A successful response contains an empty body. The error response is a JSON object with an `error` field and, in some cases, an `error_description` field.

**Endpoint errors**
+ If the token isn't present in the request or if the feature is disabled for the app client, you receive an HTTP 400 and error `invalid_request`.
+ If the token that Amazon Cognito sent in the revocation request isn't a refresh token, you receive an HTTP 400 and error `unsupported_token_type`.
+ If the client credentials aren't valid, you receive an HTTP 401 and error `invalid_client`.
+ If the token has been revoked or if the client submitted a token that isn't valid, you receive an HTTP 200 OK. 

# The IdP SAML assertion endpoint
<a name="saml2-idpresponse-endpoint"></a>

The `/saml2/idpresponse` receives SAML assertions. In service-provider-initiated (SP-initiated) sign-in, your application doesn't interact directly with this endpoint—your SAML 2.0 identity provider (IdP) redirects your user here with their SAML response. For SP-initiated sign-in, configure your IdP with the path to your `saml2/idpresponse` as the assertion consumer service (ACS) URL. For more information about session initiation, see [SAML session initiation in Amazon Cognito user pools](cognito-user-pools-SAML-session-initiation.md).

In IdP-initiated sign-in, invoke requests to this endpoint in your application after you sign in user with your SAML 2.0 provider. Your users sign in with your IdP in their browser, then your application collects the SAML assertion and submits it to this endpoint. You must submit SAML assertions in the body of a `HTTP POST` request over HTTPS. The body of your `POST` request must be a `SAMLResponse` parameter and a `Relaystate` parameter. For more information, see [Implement IdP-initiated SAML sign-in](cognito-user-pools-SAML-session-initiation.md#cognito-user-pools-SAML-session-initiation-idp-initiation).

The `saml2/idpresponse` endpoint can accept SAML assertions of up to 100,000 characters in length.

## POST `/saml2/idpresponse`
<a name="saml2-idpresponse-endpoint-post"></a>

To use the `/saml2/idpresponse` endpoint in an IdP-initiated sign-in, generate a POST request with parameters that provide your user pool with information about your user's session.
+ The app client that they want to sign in to.
+ The callback URL that they want to end up at.
+ The OAuth 2.0 scopes that they want to request in your user's access token.
+ The IdP that initiated the sign-in request.

### IdP-initiated request body parameters
<a name="saml2-idpresponse-endpoint-post-request"></a>

*SAMLResponse*  
A Base64-encoded SAML assertion from an IdP associated with a valid app client and IdP configuration in your user pool.

*RelayState*  
A `RelayState` parameter contains the request parameters that you would otherwise pass to the `oauth2/authorize` endpoint. For detailed information about these parameters, see [Authorize endpoint](authorization-endpoint.md).    
*response\$1type*  
The OAuth 2.0 grant type.  
*client\$1id*  
The app client ID.  
*redirect\$1uri*  
The URL where the authentication server redirects the browser after Amazon Cognito authorizes the user.  
*identity\$1provider*  
The name of the identity provider where you want to redirect your user.  
*idp\$1identifier*  
The identifier of the identity provider where you want to redirect your user.  
*scope*  
The OAuth 2.0 scopes that you want your user to request from the authorization server.

### Example requests with positive responses
<a name="saml2-idpresponse-endpoint-post-example"></a>

**Example – POST request**  
The following request is for an authorization code grant for a user from IdP `MySAMLIdP` in app client `1example23456789`. The user redirects to `https://www.example.com` with their authorization code, which can be exchanged for tokens that include an access token with the OAuth 2.0 scopes `openid`, `email`, and `phone`.

```
POST /saml2/idpresponse HTTP/1.1
User-Agent: USER_AGENT
Accept: */*
Host: example.auth.us-east-1.amazoncognito.com
Content-Type: application/x-www-form-urlencoded

SAMLResponse=[Base64-encoded SAML assertion]&RelayState=identity_provider%3DMySAMLIdP%26client_id%3D1example23456789%26redirect_uri%3Dhttps%3A%2F%2Fwww.example.com%26response_type%3Dcode%26scope%3Demail%2Bopenid%2Bphone
```

**Example – response**  
The following is the response to the previous request.

```
HTTP/1.1 302 Found
Date: Wed, 06 Dec 2023 00:15:29 GMT
Content-Length: 0
x-amz-cognito-request-id: 8aba6eb5-fb54-4bc6-9368-c3878434f0fb
Location: https://www.example.com?code=[Authorization code]
```

# OAuth 2.0 grants
<a name="federation-endpoints-oauth-grants"></a>

The Amazon Cognito user pool OAuth 2.0 authorization server issues tokens in response to three types of OAuth 2.0 [authorization grants](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3). You can set the supported grant types for each app client in your user pool. You can't enable *client credentials* grants in the same app client as either *implicit* or *authorization code* grants. Requests for implicit and authorization code grants begin at your [Authorize endpoint](authorization-endpoint.md) and requests for client credentials grants start at your [Token endpoint](token-endpoint.md).

**Authorization code grant**  
In response to your successful authentication request, the authorization server appends an authorization code in a `code` parameter to your callback URL. You must then exchange the code for ID, access, and refresh tokens with the [Token endpoint](token-endpoint.md). To request an authorization code grant, set `response_type` to `code` in your request. For an example request, see [Example: authorization code grant](authorization-endpoint.md#sample-authorization-code-grant). Amazon Cognito supports [Proof Key for Code Exchange (PKCE)](using-pkce-in-authorization-code.md) in authorization code grants.  
The authorization code grant is the most secure form of authorization grant. It doesn't show token contents directly to your users. Instead, your app is responsible for retrieving and securely storing your user's tokens. In Amazon Cognito, an authorization code grant is the only way to get all three token types—ID, access, and refresh—from the authorization server. You can also get all three token types from authentication through the Amazon Cognito user pools API, but the API doesn't issue access tokens with scopes other than `aws.cognito.signin.user.admin`.

**Implicit grant**  
In response to your successful authentication request, the authorization server appends an access token in an `access_token` parameter, and an ID token in an `id_token` parameter, to your callback URL. An implicit grant requires no additional interaction with the [Token endpoint](token-endpoint.md). To request an implicit grant, set `response_type` to `token` in your request. The implicit grant only generates an ID and access token. For an example request, see [Example: Token (implicit) grant without `openid` scope](authorization-endpoint.md#sample-token-grant-without-openid-scope).  
The implicit grant is a legacy authorization grant. Unlike with the authorization code grant, users can intercept and inspect your tokens. To prevent token delivery through implicit grant, configure your app client to support authorization code grant only.

**Client credentials**  
Client credentials is an authorization-only grant for machine-to-machine access. To receive a client credentials grant, bypass the [Authorize endpoint](authorization-endpoint.md) and generate a request directly to the [Token endpoint](token-endpoint.md). Your app client must have a client secret and support client credentials grants only. In response to your successful request, the authorization server returns an access token.  
The access token from a client credentials grant is an authorization mechanism that contains OAuth 2.0 scopes. Typically, the token contains custom scope claims that authorize HTTP operations to access-protected APIs. For more information, see [Scopes, M2M, and resource servers](cognito-user-pools-define-resource-servers.md).  
Client credentials grants add costs to your AWS bill. For more information, see [Amazon Cognito Pricing](https://aws.amazon.com/cognito/pricing).

**Refresh token**  
You can request a refresh token grant directly from the [Token endpoint](token-endpoint.md). This grant returns new ID and access tokens in exchange for a valid refresh token.

For more perspective on these grants and their implementation, see How to use [OAuth 2.0 in Amazon Cognito: Learn about the different OAuth 2.0 grants](https://aws.amazon.com/blogs/security/how-to-use-oauth-2-0-in-amazon-cognito-learn-about-the-different-oauth-2-0-grants/) in the *AWS Security Blog*.

# Using PKCE in authorization code grants
<a name="using-pkce-in-authorization-code"></a>

Amazon Cognito supports Proof Key for Code Exchange (PKCE) authentication in authorization code grants. PKCE is an extension to the OAuth 2.0 authorization code grant for public clients. PKCE guards against the redemption of intercepted authorization codes.

## How Amazon Cognito uses PKCE
<a name="how-pkce-works"></a>

To start authentication with PKCE, your application must generate a unique string value. This string is the code verifier, a secret value that Amazon Cognito uses to compare the client requesting the initial authorization grant to the client exchanging the authorization code for tokens. 

Your app must apply an SHA256 hash to the code verifier string and encode the result to base64. Pass the hashed string to the [Authorize endpoint](authorization-endpoint.md) as a `code_challenge` parameter in the request body. When your app exchanges the authorization code for tokens, it must include the code verifier string in plaintext as a `code_verifier` parameter in the request body to the [Token endpoint](token-endpoint.md). Amazon Cognito performs the same hash-and-encode operation on the code verifier. Amazon Cognito only returns ID, access, and refresh tokens if it determines that the code verifier results in the same code challenge that it received in the authorization request.

**To implement Authorization Grant Flow with PKCE**

1. Open the [Amazon Cognito console](https://console.aws.amazon.com/cognito/home). If prompted, enter your AWS credentials.

1. Choose **User Pools**.

1. Choose an existing user pool from the list, or create a user pool. If you create a user pool, you will be prompted to set up an app client and configure managed login during the wizard.

   1. If you create a new user pool, set up an app client and configure managed login during the guided setup.

   1. If you configure an existing user pool, add a [domain](cognito-user-pools-assign-domain.md) and a [public app client](user-pool-settings-client-apps.md), if you haven’t already.

1. Generate a random alphanumeric string, typically a universally unique identifier ([UUID](cognito-terms.md#terms-uuid)), to create a code challenge for the PKCE. This string is the value of the `code_verifier` parameter that you will submit in your request to the [Token endpoint](token-endpoint.md). 

1. Hash the `code_verifier` string with the SHA256 algorithm. Encode the result of the hashing operation to base64. This string is the value of the `code_challenge` parameter that you will submit in your request to the [Authorize endpoint](authorization-endpoint.md). 

   The following Python example generates a `code_verifier` and calculates the `code_challenge`:

   ```
   #!/usr/bin/env python3
   
   import secrets
   from base64 import urlsafe_b64encode
   from hashlib import sha256
   from string import ascii_letters
   from string import digits
   
   # use the secrets module for cryptographically strong random values
   alphabet = ascii_letters + digits
   code_verifier = ''.join(secrets.choice(alphabet) for _ in range(128))
   code_verifier_hash = sha256(code_verifier.encode()).digest()
   code_challenge = urlsafe_b64encode(code_verifier_hash).decode().rstrip('=')
   
   print(f"code challenge: {code_challenge}")
   print(f"code verifier: {code_verifier}")
   ```

   The following is an example output from the Python script:

   ```
   code challenge: Eh0mg-OZv7BAyo-tdv_vYamx1boOYDulDklyXoMDtLg
   code verifier: 9D-aW_iygXrgQcWJd0y0tNVMPSXSChIc2xceDhvYVdGLCBk-JWFTmBNjvKSdOrjTTYazOFbUmrFERrjWx6oKtK2b6z_x4_gHBDlr4K1mRFGyE8yA-05-_v7Dxf3EIYJH
   ```

1. Complete managed login sign-in with an authorization code grant request with PKCE. The following is an example URL:

   ```
   https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize?response_type=code&client_id=1example23456789&redirect_uri=https://www.example.com&code_challenge=Eh0mg-OZv7BAyo-tdv_vYamx1boOYDulDklyXoMDtLg&code_challenge_method=S256
   ```

1. Collect the authorization `code` and redeem it for tokens with the token endpoint. The following is an example request:

   ```
   POST /oauth2/token HTTP/1.1
   Host: mydomain.auth.us-east-1.amazoncognito.com
   Content-Type: application/x-www-form-urlencoded
   Content-Length: 296
   
   redirect_uri=https%3A%2F%2Fwww.example.com&
   client_id=1example23456789&
   code=7378f445-c87f-400c-855e-0297d072ff03&
   grant_type=authorization_code&
   code_verifier=9D-aW_iygXrgQcWJd0y0tNVMPSXSChIc2xceDhvYVdGLCBk-JWFTmBNjvKSdOrjTTYazOFbUmrFERrjWx6oKtK2b6z_x4_gHBDlr4K1mRFGyE8yA-05-_v7Dxf3EIYJH
   ```

1. Review the response. It will contain ID, access, and refresh tokens. For more information about using Amazon Cognito user pool tokens, see [Understanding user pool JSON web tokens (JWTs)](amazon-cognito-user-pools-using-tokens-with-identity-providers.md).

# Managed login and federation error responses
<a name="federation-endpoint-idp-responses"></a>

A sign-in process in managed login or federated sign-in might return an error. The following are some conditions that can cause authentication to end with an error.
+ A user performs an operation that your user pool can't fulfill.
+ A Lambda trigger doesn't respond with expected syntax.
+ Your identity provider (IdP) returns an error.
+ Amazon Cognito couldn't validate attribute information that your user provided.
+ Your IdP didn't send claims that map to required attributes.

When Amazon Cognito encounters an error, it communicates it in one of the following ways.

1. Amazon Cognito sends a redirect URL with the error in the request parameters.

1. Amazon Cognito displays an error in managed login.

Errors that Amazon Cognito appends to request parameters have the following format.

```
https://<Callback URL>/?error_description=error+description&error=error+name
```

When you help your users submit error information when they can't perform an operation, request that they capture the URL *and* the text or a screenshot of the page.

**Note**  
Amazon Cognito error descriptions are not fixed strings and you shouldn't use logic that relies on a fixed pattern or format.

**OIDC and social identity provider error messages**  
Your identity provider might return an error. When an OIDC or OAuth 2.0 IdP returns an error that conforms to standards, Amazon Cognito redirects your user to the callback URL and adds the provider error response to error request parameters. Amazon Cognito adds the provider name and HTTP error code to the existing error strings.

The following URL is an example redirect from an IdP that returned an error to Amazon Cognito.

```
https://www.amazon.com/?error_description=LoginWithAmazon+Error+-+400+invalid_request+The+request+is+missing+a+required+parameter+%3A+client_secret&error=invalid_request
```

Because Amazon Cognito only returns what it receives from a provider, your user might see a subset of this information. 

When your user encounters an issue with initial sign-in through your IdP, the IdP delivers any error messages directly to your user. Amazon Cognito relays an error message to your user when it generates a request to your IdP to validate your user's session. Amazon Cognito relays OAuth and OIDC IdP error messages from the following endpoints.

`/token`  
Amazon Cognito exchanges an IdP authorization code for an access token.

`/.well-known/openid-configuration`  
Amazon Cognito discovers the path to your issuer endpoints.

`/.well-known/jwks.json`  
To verify your user's JSON Web Tokens (JWTs), Amazon Cognito discovers the JSON Web Keys (JWKs) that your IdP uses to sign tokens.

Because Amazon Cognito doesn't initiate outbound sessions to SAML 2.0 providers that might return HTTP errors, your users' errors during a session with a SAML 2.0 IdP don't include this form of provider error message.