The solution proposed by @Hawk refers to a different API - Token Exchange - which can be used to retrieve (or even forge) tokens on KeyCloak. Among all different tokens you can exchange, you can retrieve tokens from configured Identity Providers, and is what we ended up using in the end.
Long story short, the "Retrieving external IDP tokens" functionality you are using will not refresh the token for you: if you plan to use it, you'll have to retrieve the refresh token and generate a new access token yourself, which is unfortunate as this would force you to have the client/secret ids of the Identity Provider on your application.
The Token Exchange API will instead refresh the token for you. You can easily retrieve the IP access token by issuing this request (the example uses python, you can obviously use any other language):
response = requests.post(
f"{ID_PROVIDER_HOST}/auth/realms/{REALM}/protocol/openid-connect/token",
data={
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"requested_token_type": "urn:ietf:params:oauth:token-type:access_token",
"requested_issuer": IDENTITY_PROVIDER_ALIAS,
"subject_token": access_token,
},
)
You need some configuration, though: first of all, Token Exchange is in "Technology Preview" as of current KeyCloak version (17), and is not enabled by default; refer to the KeyCloak documentation to see how to enable it.
Then, you'll need to enable your client to exchange IP tokens: from the administration panel of your realm:
- select "Identity Providers" from the sidebar;
- select the identity provider you want to retrieve the token from;
- select the "Permissions" tab;
- enable permissions, if not already enabled;
- click on "token exchange"
- in the "Apply Policy" table select "Create Policy" of type "Client"
- give the policy a name, and select the client you want to be able to retrieve the access tokens.