To secure a REST API with Keycloak, you register the API as a client in a Keycloak realm, give it a client ID and secret, and let it validate the JWT access tokens Keycloak issues. The part most people get wrong is thinking Keycloak protects the API for them. It does not. Keycloak issues and signs tokens; your API still has to check those tokens on every request.
Keycloak is an identity provider, not a proxy sitting in front of your endpoints. If you call the API without a token, or with an expired one, nothing in Keycloak stops that request. Your code must reject it. Plan for two jobs: getting tokens and checking tokens.
The Three Pieces You Need
Every Keycloak-protected REST API involves the same three parts. Knowing which one does what saves a lot of confused debugging.
- The realm is a container for users, clients and settings. A realm called something like
mycompanyholds everything for your API. Each realm issues its own tokens, and they are not interchangeable. A token from one realm will not validate against another. - The client is the application. Your REST API is a client of type confidential with a client secret, because a server can keep a secret. A browser app or mobile app is a public client with no secret, because anything shipped to the user can be read.
- The user signs in through Keycloak and receives tokens. Roles and scopes attached to the user decide what the token is allowed to do.
A rule of thumb: the client ID identifies who is asking, the token proves they were allowed in, and your API decides what they may touch. Only the last of those is your code's job, and it is the one that matters.
Registering Your API as a Client
Work through this once per API. The menu labels are standard Keycloak names, though they can differ slightly between versions, so look for the nearest match.
- Sign in to the admin console and select your realm, or create one with a sensible name. Keep a separate realm for testing so experiments never touch real users.
- Go to Clients and choose Create client. Set the client ID to something stable, such as
orders-api. Client IDs end up in configuration files, so choose a name you are happy to keep. - Turn on client authentication so the client gets a secret. Copy the secret into your API's configuration as an environment variable, never into source control.
- Set valid redirect URIs only if this client will run an interactive login flow. A pure resource server that only validates tokens usually needs none.
- Add roles under Client roles, for example
readerandwriter, or create realm roles if several APIs share them. - Assign roles to users or groups. A token only carries the roles the user actually holds, so an empty role list in a token usually means a missing assignment, not a broken Keycloak.
Then point your API at the realm. Most frameworks need two values: the issuer URL, shaped like https://host/realms/your-realm, and the audience you expect, which is usually your client ID or a dedicated audience mapper. With those two set, the framework can fetch the realm's public keys and verify signatures.
How Token Validation Works
Keycloak signs access tokens as JWTs with a private key. Your API fetches the matching public keys from the realm's well-known endpoint, verifies the signature, and reads the claims. Four checks matter.
- Signature. Reject anything that does not verify. Without this, anyone can write their own token.
- Expiry. Access tokens are short-lived by design. Honour the expiry claim and reject stale tokens.
- Issuer. The issuer claim must match your realm. This stops tokens from another realm or another Keycloak instance being accepted.
- Audience. The token must be intended for your API. Without an audience check, a token minted for a different service can be replayed against yours.
The audience check is the one most often skipped, and it is the one that quietly widens access. Use the framework's built-in verifier where one exists rather than parsing tokens by hand. Hand-rolled parsing tends to forget expiry or trust a token type it should not. Rely on access tokens for API calls, not ID tokens; ID tokens describe the sign-in, access tokens describe permission.
Client Credentials for Service Calls
When one service calls another with no user involved, use the client credentials grant. The calling service posts its client ID and secret to the realm's token endpoint and receives an access token representing itself. Grant that service client only the roles it needs. A reporting job that reads orders should not carry a role that can delete them.
Roles, Scopes and What to Check
Two mechanisms decide permission, and mixing them up causes most broken authorisation bugs.
Roles describe who the caller is: reader, writer, admin. They appear in the token's role claims and suit coarse rules such as "only writers may create an order". Scopes describe what access was requested: read, write, delete. They suit cases where one client needs less than another, even for the same user. Decide which one your API will trust, and check it once in a single place rather than scattering checks across handlers.
A useful pattern is to verify the token in middleware, put the caller's identity and roles into the request context, and let each endpoint check the role it needs. That keeps token handling in one spot. When a request fails, the response should be a plain 401 for a missing or invalid token and a 403 for a valid token without the needed role. Those two codes tell the caller different things, and confusing them makes debugging slow.
Checking It Actually Works
Do not trust a successful login. Test the API directly, using a tool that sends raw HTTP requests.
- Request a token from the realm's token endpoint with the client credentials grant.
- Call a protected endpoint with no token and confirm you get 401.
- Call with the token and confirm you get the expected data.
- Call with the token but request an action your role forbids, and confirm 403.
- Wait past the token lifetime and retry with the old token, expecting 401.
If every test passes except the third, the token is valid but a role or audience is missing. If the second fails, your route is not actually behind the middleware.
Renewal and Logout
Access tokens expire quickly on purpose, so a leaked token has a short life. Clients refresh them with a refresh token rather than asking the user to sign in again. For server-to-server calls, request a new token before the old one expires. For user sessions, rely on the client library's refresh handling.
Logging out means revoking the refresh token through Keycloak's logout endpoint. A revoked refresh token cannot mint new access tokens, but an access token already issued keeps working until it expires. That gap is why short lifetimes matter. When a user's access must end immediately, have the API check a revocation list or look up current roles on sensitive actions, rather than trusting the token alone.
What to Do When Tokens Are Rejected
Most rejections come from four things: a token from the wrong realm, a clock skew between servers, a missing audience mapper, or keys not refreshed after rotation. Check the issuer claim first, then the audience, then confirm the API can reach the realm's key endpoint. If it worked yesterday and fails today, suspect a key rotation before suspecting your code.