# Connect an API that uses Keycloak

If your API verifies tokens issued by a Keycloak realm, Faustine signs in as a client of that realm, with the client credentials grant. You create the client in Keycloak and enter its values in Faustine.

## Before you begin

- Faustine's servers can reach your Keycloak server over the internet. The gateway requests the token from it directly.

## Create the client in Keycloak

In the realm your API trusts, create a confidential client for Faustine: an OpenID Connect client with client authentication and service accounts turned on. Give its service account the roles your API checks. For the screens, see [Using a service account](https://www.keycloak.org/docs/latest/server_admin/#_service_accounts) in the Keycloak Server Administration Guide.

Note four values: the URL of the Keycloak server, the realm's name, and the client's ID and secret.

## Set the token endpoint on the API

1. In the portal, go to [**APIs**](https://auth.faustine.ai/go?to=%2Fintegrations%2Fapis) and select your API.
2. Select the **Authentication** tab, then **Edit**.
3. In **Sign-in method**, select **OAuth client**.
4. In **Token provider**, select **Keycloak**.
5. In **Server URL**, enter where Keycloak answers, such as `https://sso.nimbuscrm.example`. For Keycloak versions before 17, add `/auth` at the end.
6. In **Realm**, enter the name of the realm.
7. Leave **Scopes** and **Audience** empty unless your client is set up to need them.
8. Select **Save changes**.

The token URL appears under **Realm**:

```text
<SERVER_URL>/realms/<REALM>/protocol/openid-connect/token
```

## Add the client to a connection

1. Select the **Connections** tab, then **New connection**, or select an existing connection.
2. In **Credentials**, enter the **Client ID** and **Client secret**.
3. In the **Test** step, select a read operation and select **Test connection**.

**Reached the endpoint** with a `2xx` status confirms that Keycloak issued a token and your API accepted it.

## Troubleshooting

| Symptom | Cause | Fix |
| --- | --- | --- |
| `Identity provider refused the client credentials`, with `unauthorized_client` or `invalid_client` | The client secret is wrong, or the client has no service account. | Correct the secret in the connection, or turn on service accounts for the client. |
| `Identity provider refused the client credentials`, with status `404` | The token URL is wrong: the realm name, or a missing `/auth` for an older server. | Correct **Server URL** and **Realm**. |

## Next steps

- [Connect with an OAuth client](https://docs.faustine.ai/apis/connect-with-an-oauth-client/): every field of the strategy and how the token is renewed.
- [Add a connection](https://docs.faustine.ai/apis/add-a-connection/): the full wizard.
- [Authentication](https://docs.faustine.ai/apis/authentication/): the other strategies.
