# Set Up SSO with Keycloak

[OpenID Connect (OIDC)](https://openid.net/connect/) adds an identity layer to [OAuth 2.0](https://www.rfc-editor.org/rfc/rfc6749), allowing applications to verify an end user's identity and obtain basic profile information from an identity provider (IdP). In a single sign-on (SSO) deployment, users authenticate through the IdP and can access connected applications without signing in separately to each one.

[Keycloak](https://www.keycloak.org/) is an open-source identity and access management platform for applications and services. It can manage users directly or connect to external identity providers, then provide centralized authentication through OIDC or SAML. In this integration, Apache APISIX delegates browser authentication to Keycloak before proxying requests to an upstream service.

The guide shows how to configure Keycloak and APISIX for the OIDC Authorization Code flow with Proof Key for Code Exchange (PKCE). When a request does not have a valid APISIX session, APISIX redirects the browser to Keycloak. After successful authentication, APISIX exchanges the authorization code for tokens, creates a browser session, and resumes the original request.

## Prerequisite(s)[​](#prerequisites "Direct link to Prerequisite(s)")

* Install [Docker](https://docs.docker.com/get-docker/).
* Install [cURL](https://curl.se/) and [OpenSSL](https://www.openssl.org/).
* Follow the [Getting Started tutorial](https://docs.api7.ai/apisix/getting-started.md) to start APISIX with Docker.
* If you plan to use ADC, [install and configure ADC](https://docs.api7.ai/apisix/reference/adc.md) before continuing.
* If you use the Admin API examples and authentication is enabled, export an admin-role key as `ADMIN_API_KEY`. Configure the key under `deployment.admin.admin_key`. The Docker quickstart disables authentication for local evaluation; keep it enabled in production.

## Configure Keycloak[​](#configure-keycloak "Direct link to Configure Keycloak")

Start a local Keycloak server, then create a realm, an OIDC client, and a user for browser authentication.

### Start Keycloak[​](#start-keycloak "Direct link to Start Keycloak")

Start Keycloak in development mode with a temporary administrator account:

```
docker run -d --name apisix-keycloak \

  -e 'KC_BOOTSTRAP_ADMIN_USERNAME=quickstart-admin' \

  -e 'KC_BOOTSTRAP_ADMIN_PASSWORD=quickstart-admin-pass' \

  -p 8080:8080 \

  quay.io/keycloak/keycloak:26.7.3 start-dev
```

Development mode and the example credentials are intended only for local testing. For a production deployment, use HTTPS, a production database, and a permanent administrator account.

Open `http://localhost:8080/admin/` and sign in with the administrator username `quickstart-admin` and password `quickstart-admin-pass`.

### Create a Realm[​](#create-a-realm "Direct link to Create a Realm")

A Keycloak realm isolates users, clients, roles, and other authentication resources. Create a realm for this guide:

1. Select **Manage realms → Create realm**.
2. Enter `quickstart-realm` as the realm name.
3. Select **Create**.

![Create a realm in Keycloak](https://static.api7.ai/uploads/2026/09/10/V0JjfJ1S_keycloak-01-create-realm.jpg)

### Create an OIDC Client[​](#create-an-oidc-client "Direct link to Create an OIDC Client")

Register APISIX as a confidential OIDC client:

1. Select **Clients → Create client**.

2. Keep **Client type** set to **OpenID Connect**, enter `apisix-quickstart-client` as the client ID, and select **Next**.

   ![Create an OIDC client in Keycloak](https://static.api7.ai/uploads/2026/09/10/Tm1RZ8Un_keycloak-02-create-client-general.jpg)

3. Turn on **Client authentication** and **Standard flow**. Leave the other authentication flows off, then select **Next**.

4. Enter `http://localhost:9080/anything/user/callback` under **Valid redirect URIs** and select **Save**.

   ![Configure the APISIX redirect URI in Keycloak](https://static.api7.ai/uploads/2026/09/10/TAB5vkNA_keycloak-03-configure-client-redirect-no-banner.jpg)

5. In **Capability config**, turn on **Require PKCE**, select **S256** as the PKCE method, and select **Save**.

The redirect URI identifies the APISIX endpoint where Keycloak returns the browser after authentication. In production, use an HTTPS endpoint that users can reach and register that exact URI in Keycloak.

### Create a User[​](#create-a-user "Direct link to Create a User")

Create a user that can sign in through the new realm:

1. Select **Users → Create new user**.

2. Configure the following fields and select **Create**:

   | Field          | Value                         |
   | -------------- | ----------------------------- |
   | **Username**   | `quickstart-user`             |
   | **Email**      | `quickstart-user@example.com` |
   | **First name** | `Quickstart`                  |
   | **Last name**  | `User`                        |

   ![Create a user in Keycloak](https://static.api7.ai/uploads/2026/09/10/GyVfNuXE_keycloak-04-create-user.jpg)

3. Open the **Credentials** tab and select **Set password**.

4. Enter `quickstart-user-pass` in **Password** and **Password confirmation**, turn off **Temporary**, and select **Save**.

5. Select **Save password** in the confirmation dialog.

![Set a permanent user password in Keycloak](https://static.api7.ai/uploads/2026/09/10/VUXdeYHg_keycloak-05-set-user-password.jpg)

### Save the OIDC Configuration[​](#save-the-oidc-configuration "Direct link to Save the OIDC Configuration")

Select **Realm settings**. On the **General** tab, find **Endpoints** and open **OpenID Endpoint Configuration**.

![Find the OpenID discovery endpoint in Keycloak](https://static.api7.ai/uploads/2026/09/10/3FLqllVV_keycloak-06-openid-endpoint.jpg)

The discovery endpoint has the following path:

```
/realms/quickstart-realm/.well-known/openid-configuration
```

The APISIX container and the browser must be able to reach Keycloak at the same hostname. Save a reachable host address and the discovery endpoint as environment variables, replacing the example address:

```
export KEYCLOAK_HOST=192.168.1.100

export KEYCLOAK_DISCOVERY="http://${KEYCLOAK_HOST}:8080/realms/quickstart-realm/.well-known/openid-configuration"
```

Select **Clients → apisix-quickstart-client → Credentials** and copy the client secret.

![Copy the Keycloak client secret](https://static.api7.ai/uploads/2026/09/10/h0u5ku7U_keycloak-07-client-secret.jpg)

Save the client ID and secret as environment variables:

```
export KEYCLOAK_CLIENT_ID=apisix-quickstart-client

export KEYCLOAK_CLIENT_SECRET=replace-with-your-client-secret
```

Keep the client secret confidential. Store production credentials in a secret manager and rotate them according to the organization's credential-rotation policy.

## Configure APISIX[​](#configure-apisix "Direct link to Configure APISIX")

Configure a route that authenticates browser requests before forwarding them to [httpbin.org](https://httpbin.org/), a public HTTP request and response service. The `/anything/user/*` endpoint returns request details for verification.

Generate a unique secret that APISIX will use to encrypt and authenticate the browser session cookie:

```
export APISIX_SESSION_SECRET="$(openssl rand -hex 32)"
```

Choose either the Admin API or ADC to configure the route.

* Admin API
* ADC

Create the route through the Admin API:

```
curl "http://127.0.0.1:9180/apisix/admin/routes/keycloak-sso" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  --data-binary @- <<EOF

{

  "uri": "/anything/user/*",

  "plugins": {

    "openid-connect": {

      "client_id": "$KEYCLOAK_CLIENT_ID",

      "client_secret": "$KEYCLOAK_CLIENT_SECRET",

      "discovery": "$KEYCLOAK_DISCOVERY",

      "redirect_uri": "http://localhost:9080/anything/user/callback",

      "bearer_only": false,

      "use_pkce": true,

      "scope": "openid profile email",

      "session": {

        "secret": "$APISIX_SESSION_SECRET"

      },

      "set_access_token_header": false,

      "set_id_token_header": false,

      "set_userinfo_header": false

    },

    "proxy-rewrite": {

      "headers": {

        "remove": ["Authorization", "Cookie"]

      }

    }

  },

  "upstream": {

    "type": "roundrobin",

    "nodes": {

      "httpbin.org:80": 1

    }

  }

}

EOF
```

❶ `discovery`: URI of the Keycloak realm's OIDC discovery document.

❷ `redirect_uri`: URI where Keycloak returns the browser after authentication. It must match the valid redirect URI configured for the Keycloak client.

❸ `bearer_only` and `use_pkce`: Start browser authentication when no valid session exists and send an S256 PKCE challenge during authorization.

❹ `set_access_token_header`, `set_id_token_header`, and `set_userinfo_header`: Set to `false` to prevent APISIX from adding tokens and user information to upstream request headers.

❺ `proxy-rewrite.headers.remove`: Removes the original authorization header and the entire cookie header, including the APISIX session cookie, before proxying the request. Review this setting if the upstream application requires cookies.

Create an `adc.yaml` file with the route configuration:

adc.yaml

```
services:

  - name: keycloak-sso

    routes:

      - name: keycloak-sso

        uris:

          - /anything/user/*

        plugins:

          openid-connect:

            client_id: "${KEYCLOAK_CLIENT_ID}"

            client_secret: "${KEYCLOAK_CLIENT_SECRET}"

            discovery: "${KEYCLOAK_DISCOVERY}"

            redirect_uri: http://localhost:9080/anything/user/callback

            bearer_only: false

            use_pkce: true

            scope: openid profile email

            session:

              secret: "${APISIX_SESSION_SECRET}"

            set_access_token_header: false

            set_id_token_header: false

            set_userinfo_header: false

          proxy-rewrite:

            headers:

              remove:

                - Authorization

                - Cookie

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ `discovery`: URI of the Keycloak realm's OIDC discovery document.

❷ `redirect_uri`: URI where Keycloak returns the browser after authentication. It must match the valid redirect URI configured for the Keycloak client.

❸ `bearer_only` and `use_pkce`: Start browser authentication when no valid session exists and send an S256 PKCE challenge during authorization.

❹ `set_access_token_header`, `set_id_token_header`, and `set_userinfo_header`: Set to `false` to prevent APISIX from adding tokens and user information to upstream request headers.

❺ `proxy-rewrite.headers.remove`: Removes the original authorization header and the entire cookie header, including the APISIX session cookie, before proxying the request. Review this setting if the upstream application requires cookies.

ADC reconciles services as desired state. The label selector limits this example to its own labeled resources. Preview the scoped changes and confirm that they contain no unintended updates or deletions:

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=keycloak-sso
```

Synchronize the reviewed service configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=keycloak-sso
```

## Verify Authentication[​](#verify-authentication "Direct link to Verify Authentication")

Navigate to `http://localhost:9080/anything/user/get` in a browser. APISIX redirects you to Keycloak. Sign in with the username `quickstart-user` and password `quickstart-user-pass`.

![Sign in to the Keycloak realm](https://static.api7.ai/uploads/2026/09/10/0trHyY6w_keycloak-08-user-sign-in.jpg)

After successful authentication, Keycloak returns the browser to APISIX, and APISIX forwards the request to httpbin.org. The response should contain fields similar to these:

```
{

  "args": {},

  "data": "",

  "files": {},

  "form": {},

  "headers": {

    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",

    "Accept-Encoding": "gzip, deflate",

    "Accept-Language": "en-CA,en-US;q=0.9,en;q=0.8",

    "Host": "localhost",

    "Priority": "u=0, i",

    "Sec-Fetch-Dest": "document",

    "Sec-Fetch-Mode": "navigate",

    "Sec-Fetch-Site": "cross-site",

    "Upgrade-Insecure-Requests": "1",

    "User-Agent": "Mozilla/5.0 ...",

    "X-Amzn-Trace-Id": "Root=1-...",

    "X-Forwarded-Host": "localhost:9080"

  },

  "json": null,

  "method": "GET",

  "origin": "192.168.155.1, xxx.xxx.xxx.xxx",

  "url": "http://localhost:9080/anything/user/get"

}
```

Header values and the reported origin address vary by browser and network environment.

The upstream request headers should not include the APISIX session cookie, access token, ID token, or user-information header. Reload the page to verify that APISIX reuses the browser session without redirecting you to Keycloak.

## Next Steps[​](#next-steps "Direct link to Next Steps")

You have now configured APISIX to authenticate browser requests with Keycloak. To authorize requests from services without an end-user session, see [Authorize M2M Requests with Keycloak](https://docs.api7.ai/apisix/how-to-guide/authentication/authorize-m2m-requests-with-keycloak.md). See the [`openid-connect` plugin reference](https://docs.api7.ai/hub/openid-connect/configuration.md) for more configuration options.
