# Token Exchange Flow (External IDP Integration)

This flow allows applications to exchange a valid security token issued by an external Identity Provider (IDP), such as Okta, for an eGain access token. This is ideal for Single Sign-On (SSO) scenarios where you want to leverage existing sessions to call eGain APIs.

## **Prerequisites & Guidelines**

* **SSO Configuration**: The external IDP must be registered and stored in the **SSO Provider** configuration section of the Administrator Console.
* **User Matching**: The user identity (e.g., email) contained within the external token's claims must exist in the eGain database.
* **Client Enablement**: The Client Application must have the "Token Exchange Grant Type" enabled.


## **Exchange an External Token for an eGain Token**

* **Method**: `POST`
* **Endpoint**: Your Token URL (from your client application's [metadata](/developer-portal/guides/authentication/metadata)).
  * Example Token URL for a Client App:
    * `https://ai.egain.cloud/system/auth/TMPRODB88619984-U/oauth2/token`


**Headers:**

| Header | Value |
|  --- | --- |
| `Content-Type` | `application/x-www-form-urlencoded` |


**Body Parameters (`application/x-www-form-urlencoded`):**

| Parameter | Relevance | Description |
|  --- | --- | --- |
| `grant_type` | Required | Must be set to `urn:ietf:params:oauth:grant-type:token-exchange`. |
| `subject_token` | Required | The valid JWT access token issued by your external IDP (e.g., Okta). |
| `subject_token_type` | Required | The type of token being provided. Use `urn:ietf:params:oauth:token-type:access_token`. |
| `registration_id` | Required | The unique identifier generated in the Administrator Console for the external IDP registration. |
| `client_id` | Required | The eGain Client ID for your application. |
| `client_secret` | Required | The eGain Client Secret for your application. |
| `scope` | Optional | A space-separated list of eGain scopes requested for the new token. |


**Validation Logic:** During this request, eGain verifies the token's signature using the external IDP's JWK URL, ensures the `iss` (issuer) and `aud` (audience) claims match your registration, and confirms the user exists within eGain.

* **Example Token Exchange cURL:**



```curl
curl --location --request POST 'https://ai.egain.cloud/system/auth/TMPRODB88619984-U/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
--data-urlencode 'subject_token=EXTERNAL_IDP_JWT_TOKEN' \
--data-urlencode 'subject_token_type=urn:ietf:params:oauth:token-type:access_token' \
--data-urlencode 'registration_id=okta_sso_config_01' \
--data-urlencode 'client_id=b4b2c1d9-4c19-4e8a-8e7a-9a0b1c2d3e4f' \
--data-urlencode 'client_secret=aBcDeFgHiJkLmNoPqRsTuVwXyZ12345'
```

**Next Steps:**

- [Make Authenticated Requests](/developer-portal/guides/authentication/making-requests)