Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Secure an application with Keycloak (OIDC)

14 min read
Improve this page

This lesson shows how to connect an existing application to Keycloak with OpenID Connect. You no longer write a login page: your application redirects the user to Keycloak, which authenticates them and sends back a signed token. The lesson covers choosing the client type, redirect URIs, enabling PKCE, and the starting point for protecting an API with the tokens you obtain. It is aimed at developers or administrators who already have a Keycloak realm (the space that groups users and clients) and want to connect a real application to it.

This lesson is the hands-on side of OIDC with Keycloak. If the notions of token, scope or flow are not clear yet, read the concepts first: OpenID Connect (in French) for authentication and OAuth 2.x (in French) for delegated access to APIs. Here, we configure.

What you will learn

  • Choose the right client type for your application (SPA, backend, service)
  • Create an OIDC client in a realm, in the console and on the command line
  • Configure redirect URIs and web origins to avoid redirect and CORS errors
  • Enable PKCE to protect the authorization flow
  • Read the discovery document to find the standard OIDC endpoints
  • Identify what an API that receives a token must check (audience, scope), covered in a dedicated lesson

Prerequisites

Before you start, you need:

  • A working Keycloak instance. See Install Keycloak with Docker (in French).
  • An application realm (never the master realm) with at least one test user. See Administer Keycloak. The examples use the lab realm and the user alice.
  • An application to connect: the language does not matter, the principle is the same. What changes is the OIDC library on the application side.

Step 1 - Choose the right client type

A client in Keycloak represents an application that is allowed to request tokens. The first choice, the one that drives the whole security model, is public or confidential. The difference comes down to a single point: can the application keep a secret?

Client typeCan keep a secretTypical applicationRecommended flow
ConfidentialYes (server code)Web application with a backend, APIAuthorization Code + PKCE
PublicNo (visible code)SPA (React, Vue), mobile application, CLIAuthorization Code + PKCE
Confidential + service accountYesService with no user (cron, backend-to-backend)Client Credentials

A SPA (single-page application) or a mobile application runs entirely on the user's device: its JavaScript code or its binary can be read, so it cannot store a secret. It is public. By contrast, a Node, Django or Spring backend keeps its secret on the server: it is confidential.

Step 2 - Create the client for a web application

Take a classic web application with a backend, served at https://app.exemple.fr. After login, Keycloak must send the user back to a callback URL: https://app.exemple.fr/callback.

  1. Select your realm (lab) in the selector at the top left, then Clients > Create client.

  2. General settings:

    • Client type: OpenID Connect
    • Client ID: webapp-demo
  3. Capability config:

    • Client authentication: On (this is what makes the client confidential)
    • Authorization: Off (fine-grained permissions are a separate topic)
    • Standard flow: checked (this is the Authorization Code flow)
    • Direct access grants: unchecked
  4. Login settings:

    • Valid redirect URIs: https://app.exemple.fr/callback
    • Web origins: https://app.exemple.fr
  5. Save. The secret is available in the Credentials tab.

Step 3 - Enable PKCE

PKCE (Proof Key for Code Exchange, pronounced "pixy") prevents interception of the authorization code. The application generates a random secret for each login, sends its hash to Keycloak, then proves it holds the original when it exchanges the code for a token. Without the original secret, a stolen code is useless.

PKCE is set per client. In the Keycloak 26.7 console, the setting is in the Settings tab, Capability config section:

  1. Open the webapp-demo client, Settings tab, and scroll down to the Capability config section.

  2. Turn on Require PKCE. The PKCE Method field appears: keep or choose S256.

  3. Click Save.

The Capability config section also appears while you create a client, so you can enable PKCE from the start. Older versions of the console put this setting in the Advanced tab, "Advanced settings" section, under the label "Proof Key for Code Exchange Code Challenge Method". If your console does not show Require PKCE, look there.

Step 4 - Understand the OIDC endpoints

Your OIDC library (on the application side) needs to know the Keycloak URLs: where to redirect the user, where to exchange the code, where to validate tokens. All these addresses are published in one place, the discovery document (excerpt below):

Terminal window
curl -s http://localhost:8080/realms/lab/.well-known/openid-configuration
{
"issuer": "http://localhost:8080/realms/lab",
"authorization_endpoint": "http://localhost:8080/realms/lab/protocol/openid-connect/auth",
"token_endpoint": "http://localhost:8080/realms/lab/protocol/openid-connect/token",
"userinfo_endpoint": "http://localhost:8080/realms/lab/protocol/openid-connect/userinfo",
"jwks_uri": "http://localhost:8080/realms/lab/protocol/openid-connect/certs",
"end_session_endpoint": "http://localhost:8080/realms/lab/protocol/openid-connect/logout"
}

Most libraries (Spring Security, oidc-client-ts, authlib for Python, oauth2-proxy) only ask for the issuer and discover the rest automatically. Remember these three addresses:

  • authorization_endpoint: where the application sends the user to sign in.
  • token_endpoint: where the application exchanges the code for a token.
  • jwks_uri: the public keys used to verify the signature of tokens without calling Keycloak on every request.

Step 5 - What must the API that receives the token do?

A token protects nothing until an API requires it. The API verifies the signature with the keys from the jwks_uri seen in the previous step, then the issuer (iss), the expiry (exp), the audience (aud, the intended recipient of the token) and the route's scope (the permission requested): a valid signature only proves that the token comes from Keycloak, not that it is meant for this API. For a service with no user, the client_credentials flow of a confidential client with a service account issues the token.

The lesson Protect an API with access tokens using Keycloak (in French) puts all of this into practice: audience and scopes in Keycloak, an API that answers 401 or 403, a client using client credentials without exposing its secret, then device grant and token exchange.

Security

A few non-negotiable rules for a sound OIDC integration:

  • PKCE S256 mandatory for every authorization flow, public or confidential. Never plain.
  • Exact redirect URIs, never a broad wildcard nor localhost:* in production.
  • Confidential client whenever possible: if the application has a backend, it keeps a secret, so it is confidential.
  • Client secret treated like a password: never in the Git repository, never in front-end code. Use an environment variable or a vault. See HashiCorp Vault.
  • Short token lifetime (5 minutes by default) and renewal through a refresh token. Do not lengthen it for convenience.
  • HTTPS everywhere: a token that travels in clear text is a stolen token. In production, Keycloak and your applications sit behind TLS.
  • Systematic validation of the signature, issuer, audience and scope on the API side, detailed in Protect an API with access tokens (in French).

Troubleshooting

SymptomLikely causeFix
Invalid parameter: redirect_uriThe app's callback URL is not in the Valid redirect URIsAdd the exact URL in the client configuration
CORS error in the browser consoleWeb origins not set for a SPAAdd the origin (https://app.exemple.fr) in Web origins
unauthorized_client and Invalid client or Invalid client credentials at the token endpoint (HTTP 401)Wrong or missing secret on a confidential client (event invalid_client_credentials)Copy the secret again from Credentials, without a trailing newline
invalid_client at the token endpointUnknown client_id or disabled client (event client_not_found for an unknown client)Check the client identifier
unauthorized_client with client_credentialsService accounts roles disabled (Client not enabled to retrieve service account) or public client (Public client not allowed to retrieve service account)Enable Service accounts roles on a confidential client
Account is not fully set upThe user has a pending required action (incomplete profile)Fill in firstName/lastName and clear the account's required actions
Token accepted but roles missingThe scope or mapper does not carry the rolesCheck the client's Client scopes and mappers

In Keycloak 26.7.0, a wrong secret gives unauthorized_client rather than invalid_client, even though RFC 6749 (section 5.2) specifies invalid_client for a failed client authentication: do not rely on the error code alone, read the event. A public client called with an extra client_secret does not fail because of it: Keycloak ignores the secret.

Key takeaways

  • A Keycloak client represents an application; the first choice is public or confidential, depending on whether it can keep a secret.
  • Authorization Code + PKCE S256 is the standard for any interactive application. The implicit flow is discouraged by RFC 9700.
  • Exact redirect URIs protect against token theft; web origins unblock CORS calls from SPAs.
  • The .well-known/openid-configuration document gives all the endpoints; most libraries only need the issuer.
  • The client_credentials flow authenticates a service with no user, through a confidential client with a service account.
  • An API always validates the signature (through jwks_uri), the issuer, the audience and the scope before trusting a token; the lesson Protect an API (in French) puts this into practice.