Keycloak and Apigee: VerifyJWT and OAuthV2 Integration. Use Keycloak as the token issuer for Apigee X and hybrid: validate tokens with VerifyJWT against the realm JWKS, pin RS256, check iss and aud, rotate keys safely.
To use Keycloak with Google Apigee, let Keycloak issue the access tokens and have Apigee validate them. Add a VerifyJWT policy to your proxy that reads the realm’s JWKS endpoint, pins the algorithm to RS256, and checks the issuer and the audience. Reach for the OAuthV2 policy with an external access token only when you need Apigee API products and quotas tied to Keycloak tokens.
This guide is for engineers who already run Keycloak and Apigee and now want Keycloak to be the token issuer for their Apigee proxies. It covers Apigee X and Apigee hybrid, where Google documents both policies on the same reference pages, and it uses the Keycloak 26 admin console. The older Apigee Edge has its own documentation at docs.apigee.com and is not covered here. If you run Kong instead, our Keycloak and Kong API Gateway guide is the sibling of this post.
The client gets a token from Keycloak (1) and sends it to Apigee as a Bearer token (2). VerifyJWT finds the token’s key in the realm’s JWKS and checks the RS256 signature (3), then checks the issuer, audience and expiry (4). Only a token that passes everything reaches the backend (5).
Should you use VerifyJWT or OAuthV2 for Keycloak tokens?
Both policies can sit in front of the same Keycloak realm, but they do different jobs. VerifyJWT checks a signed token on its own: it fetches the realm’s public keys, verifies the signature, and compares the claims with what you configured, so Apigee never stores anything about the token. The OAuthV2 policy works with Apigee’s own token store. In the external token pattern, Apigee receives the Keycloak token once, imports it into that store, and associates it with an Apigee app, which is what lets API products and product quotas apply to it.
| VerifyJWT with JWKS | OAuthV2 with an external access token | |
|---|---|---|
| What Apigee checks | Signature, algorithm, iss, aud, exp |
That the stored token exists and is valid for the app |
| Apigee setup | One policy per proxy | A token proxy, an Apigee app per Keycloak client, products |
| API products and product quotas | No, you authorize on claims | Yes |
| Calls to Keycloak per request | None (the JWKS is cached) | None after the token is imported |
| Token size limit | None, nothing is stored | 2 KB or smaller |
Start with VerifyJWT. It needs the least setup, it keeps Keycloak as the single place where tokens are issued and described, and every check it does is visible in one policy file. Move to the OAuthV2 pattern when your API program already runs on Apigee API products, for example when partners subscribe to products in a developer portal and you meter them with product quotas.
Token introspection is a third option, which you can mostly skip. Introspection, defined in RFC 7662, means the gateway asks the authorization server about each token, and the server returns a JSON document “representing the meta information surrounding the token, including whether this token is currently active”. Apigee would make that call with a ServiceCallout to Keycloak’s introspection endpoint on every request, which adds a network round trip to each API call. It is only worth that cost when you need a revoked token to stop working immediately or when your tokens are opaque rather than JWTs. Our post on verifying a Keycloak access token on the backend compares local validation and introspection in more detail.
Prerequisites
- A Keycloak realm (we use
demo) and an admin account for it. - An Apigee X or hybrid organization, with a proxy for your API (we use one at
/orders) and permission to edit and deploy it. - For Apigee hybrid, a runtime that can reach your Keycloak hostname over HTTPS, because the gateway fetches the JWKS from it.
curlandjqin a terminal.
Step 1: Create a client for the caller
In the demo realm, open Clients and choose Create client. Name it orders-client, turn Client authentication on and select Service accounts roles, which enables the client credentials grant for this machine-to-machine caller. After you save, copy the secret from the Credentials tab. Our guide to Keycloak machine-to-machine authentication explains service accounts in more depth.
Step 2: Put your API in the token’s audience
Apigee will only accept tokens whose aud claim names your API, so Keycloak has to put it there. Keycloak’s default Audience Resolve mapper fills aud “based on the applied client roles”, so for an API without client roles in the token you add a hardcoded audience yourself.
Open orders-client, go to the Client scopes tab and select its dedicated scope, orders-client-dedicated. Choose Add mapper, then By configuration, then Audience. Name it orders-api audience, set Included Custom Audience to orders-api, keep Add to access token on, and save. Every token this client receives now carries orders-api in aud.
Two more values come from the realm, and you will paste both into Apigee in the next step. The issuer is https://keycloak.example.com/realms/demo, and the JWKS endpoint, where the realm publishes its public keys, is that issuer followed by /protocol/openid-connect/certs. Use the exact hostname your clients use to get tokens, because Keycloak writes the host into the iss claim and Apigee compares it as a string.
Step 3: Add a VerifyJWT policy to the proxy
In the Apigee proxy editor, add a VerifyJWT policy named VJ-Keycloak with this configuration:
<VerifyJWT name="VJ-Keycloak">
<DisplayName>VJ-Keycloak</DisplayName>
<Algorithm>RS256</Algorithm>
<PublicKey>
<JWKS uri="https://keycloak.example.com/realms/demo/protocol/openid-connect/certs"/>
</PublicKey>
<Issuer>https://keycloak.example.com/realms/demo</Issuer>
<Audience>orders-api</Audience>
<TimeAllowance>30s</TimeAllowance>
<IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
</VerifyJWT>
Attach it as the first step of the proxy endpoint’s PreFlow request, so nothing else runs for a request with a bad token. Without a Source element, the policy reads the token from the Authorization header and removes the Bearer prefix itself. Each element does one check:
Algorithmaccepts only RS256. Check the Default Signature Algorithm on the Tokens tab of your realm settings, which the server administration guide’s section on session and token timeouts describes as “the default algorithm used to assign tokens for the realm”, and use that value. The policy can take a comma-separated list, but the VerifyJWT reference’s Algorithm element says “you cannot combine HS* algorithms with any others”, and you want one value here anyway.JWKS uripoints at the realm’s keys. The policy reads thekid(key ID) from the token header and, in Google’s words, “If the inbound JWT bears a key ID which is present in the JWKS, then the policy will use the correct public key to verify the JWT signature.”Issuermust match theissclaim exactly, so tokens from another realm or another Keycloak are refused even when they are well signed.Audiencemust match theaudclaim, which is why Step 2 matters.TimeAllowancegives a small grace period for clock differences when checkingexpandnbf.
If your realm uses another algorithm, such as ES256 for an elliptic-curve key, set that value instead, but always set exactly the algorithm your realm signs with.
Step 4: Check scopes or roles for each operation
VerifyJWT answers whether a token is genuine and meant for this API. It does not say which operations the caller may use. After the policy runs, Apigee exposes the token’s claims as flow variables such as jwt.VJ-Keycloak.decoded.claim.scope, and you can use them in step conditions.
In Keycloak, create a client scope named orders:read with Include in token scope on, and add it to orders-client as an Optional scope, so it appears in the token’s scope claim only when the caller asks for it. In Apigee, add a RaiseFault policy that returns 403:
<RaiseFault name="RF-Missing-Scope">
<FaultResponse>
<Set>
<StatusCode>403</StatusCode>
<ReasonPhrase>Forbidden</ReasonPhrase>
</Set>
</FaultResponse>
</RaiseFault>
Then run it on the read flow when the scope is missing:
<Step>
<Name>RF-Missing-Scope</Name>
<Condition>NOT (jwt.VJ-Keycloak.decoded.claim.scope ~~ "(.* )?orders:read( .*)?")</Condition>
</Step>
This keeps the 401 and 403 cases apart: a bad token fails in VerifyJWT, and a good token without permission fails here. If you authorize on Keycloak client roles instead of scopes, they arrive nested under resource_access in the token, which is easier to read in a JavaScript policy or in the backend than in a condition.
Somewhere to run this that stays patched
Everything above works the same on Skycloak, because it is real upstream Keycloak rather than a fork. What changes is who handles the upgrades, backups and security patches afterwards.
Step 5 (optional): Import Keycloak tokens for API products and quotas
Use this step only if you need Apigee API products. Google’s guide to using a third-party OAuth system describes the pattern, and it requires a matching app for every token: “Every access_token in Apigee, whether generated by Apigee or generated by an external system and then imported into Apigee, must be associated to a client application - indicated by the client_id.” So each Keycloak client that calls your APIs needs an Apigee app whose consumer key is the same client ID, which the guide says you can import through the Apigee administrative API. You then subscribe that app to the products it may use, and the products carry the quotas.
The flow runs through a token proxy in Apigee that the client calls instead of Keycloak:
- A ServiceCallout sends the client’s
client_idandclient_secretto the Keycloak token endpoint,https://keycloak.example.com/realms/demo/protocol/openid-connect/token, with the client credentials grant. - An ExtractVariables policy copies
access_tokenfrom Keycloak’s response into a variable namedexternal_access_token. - An AssignMessage policy sets
oauth_external_authorization_statustotrue. The guide explains that when this is true, “Apigee does not attempt to validate the client credentials”, which is correct here because Keycloak just did. - An OAuthV2 policy stores the token:
<OAuthV2 name="OAuth-v20-Store-External-Token">
<ExternalAccessToken>external_access_token</ExternalAccessToken>
<ExternalAuthorization>true</ExternalAuthorization>
<Operation>GenerateAccessToken</Operation>
<StoreToken>true</StoreToken>
<SupportedGrantTypes>
<GrantType>client_credentials</GrantType>
</SupportedGrantTypes>
<GenerateResponse enabled="true"/>
</OAuthV2>
Apigee expects the client ID in the form data (request.formparam.client_id), so the client posts its credentials as a form, the same way it would to Keycloak. Your API proxies then run an OAuthV2 policy with the VerifyAccessToken operation, and a Quota policy with UseQuotaConfigInAPIProduct applies the limits from the product. Keep two things in mind. Imported tokens must be 2 KB or smaller, and a Keycloak token that carries many roles can pass that size, so map only the roles each client needs. The Keycloak scopes a client can request and the Apigee products its app holds also describe the same access in two places, so change them together.
How do you rotate Keycloak keys without breaking Apigee?
The VerifyJWT reference’s JWKS element says that when the JWKS comes from a URL, “Apigee caches the JWKS for a period of 300 seconds. When the cache expires, Apigee fetches the JWKS again.” If Keycloak starts signing with a brand new key, gateways can hold a cached JWKS without that key’s kid for up to five minutes and reject the new tokens until the cache expires. To avoid that, publish the new key before anything is signed with it.
Keycloak gives you the pieces for this. The realm has one active key pair that creates new signatures while passive keys can still verify earlier ones, and the realm’s certs endpoint serves, in the words of the server administration guide’s list of OIDC URI endpoints, “the public keys used to verify any JSON Web Token”. The server administration guide’s section on rotating keys recommends that you “start by creating new keys with a higher priority than the existing active keys”. With Apigee in front, do it in this order:
- Under Realm settings, Keys, Add provider, add a new RSA key provider with a higher priority than the current one and Active off. The key is now published but not used to sign.
- Fetch the JWKS endpoint with
curland confirm it lists the new key’skid, then wait more than 300 seconds, so every gateway has fetched a JWKS that contains both keys. - Turn Active on for the new provider. New tokens now carry its
kid, and tokens signed with the old key still verify. - When the longest-lived token signed with the old key has expired, disable the old provider, and delete it later.
Add the new key as passive (1) and wait past Apigee’s 300 second JWKS cache (2). Then make it active so new tokens use it (3), and retire the old key only after its tokens have expired (4).
Why pin the algorithm and check iss and aud?
These three checks close the gaps that most often turn into gateway vulnerabilities. The JWT Best Current Practices, RFC 8725, says in section 3.1 that libraries “MUST enable the caller to specify a supported set of algorithms”, because a verifier that trusts the token’s own alg header can be tricked into using the wrong kind of key or no signature at all. Our posts on JWT algorithm confusion and the none algorithm and on CVE-2026-5430 in WSO2 API Manager show what happens when a gateway gets this wrong.
The same RFC says in section 3.9 that when one issuer serves several applications, “the relying party or application MUST validate the audience value”. A realm often issues tokens for many clients, and without the Audience element a token meant for an internal tool would be accepted by your public orders API, because its signature and issuer are just as valid. We covered a library that skipped this check in our post on CVE-2026-50627 in Apache CXF. The Issuer check plays the same role across realms, and the kid lookup follows RFC 7517, section 4.5, where “The “kid” (key ID) parameter is used to match a specific key.”
Test it
Get a token from Keycloak with the client credentials grant and look at its claims:
TOKEN=$(curl -s -X POST \
https://keycloak.example.com/realms/demo/protocol/openid-connect/token \
-d grant_type=client_credentials \
-d client_id=orders-client \
-d client_secret="$CLIENT_SECRET" \
-d scope=orders:read | jq -r .access_token)
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{iss, aud, scope, exp}'
Check that iss is your realm URL, aud contains orders-api and scope contains orders:read. Then call the proxy with the token, and once more without the scope, and once with a damaged signature:
curl -i https://api.example.com/orders -H "Authorization: Bearer $TOKEN"
curl -i https://api.example.com/orders -H "Authorization: Bearer ${TOKEN%??????}AAAAAA"
The first call should reach your backend. A token requested without scope=orders:read should get 403 from the RaiseFault policy, and the token with the end of its signature replaced should be rejected by VerifyJWT before the backend sees it. Also try a token from a second client that has no audience mapper, which VerifyJWT should reject on aud. The Debug tool in the Apigee console shows which policy stopped each request.
Troubleshooting
- Every token fails on the issuer. The
issclaim carries the hostname the client used to reach Keycloak, so a token fetched through an internal address has a different issuer than one fetched through the public name. Copyissfrom a decoded token into theIssuerelement, and have clients use one hostname. - Tokens fail on the audience. The mapper from Step 2 is missing, sits on another client, or has Add to access token off. Decode a fresh token and check
audbefore changing Apigee. - Requests fail for a few minutes after a key change. Keycloak signed with a key that Apigee’s cached JWKS did not have yet. Follow the rotation order above, publishing the key as passive first.
- Apigee hybrid cannot fetch the JWKS. The runtime needs outbound HTTPS to your Keycloak hostname and must trust its certificate.
- The token import in Step 5 fails. Check that an Apigee app exists with the Keycloak client ID as its consumer key, that the request sends
client_idas form data, and that the token is 2 KB or smaller.
FAQ
Can Apigee use Keycloak as its OAuth provider?
Yes. Keycloak issues the tokens, and Apigee either validates them directly with VerifyJWT or imports them with the OAuthV2 policy as external access tokens. Google documents the import pattern in its guide to using a third-party OAuth system.
How often does Apigee refresh the Keycloak JWKS?
When the JWKS comes from a URL, the VerifyJWT reference says Apigee caches it for 300 seconds and then fetches it again. Publish new Keycloak keys as passive at least that long before they start signing.
Does Apigee notice when a Keycloak token is revoked?
Not with VerifyJWT, which only checks the signature and claims, so a revoked token works until it expires. Keep access token lifetimes short, or call Keycloak’s introspection endpoint from Apigee for the APIs where immediate revocation matters, accepting the extra call per request.
Do I need the OAuthV2 policy if I already use VerifyJWT?
Only if you want Apigee API products, product quotas or developer apps tied to Keycloak tokens. For authentication and claim-based authorization, VerifyJWT is enough on its own.
Next steps
Start with the VerifyJWT policy and the audience mapper, run the three curl tests, and add the scope checks for each operation. Plan your first key rotation in the passive-first order before you need it, and add the OAuthV2 import only if your API program runs on Apigee products. If you would rather not run the Keycloak side yourself, set up a realm on Skycloak’s managed Keycloak hosting and point your Apigee VerifyJWT policy at its JWKS endpoint.




