Building an Authentication System with Keycloak Token Exchange

Building an Authentication System with Keycloak Token Exchange

1. Basic Concept of Token Exchange

In a microservices architecture (MSA) environment, when it is necessary to delegate authority or reissue tokens between multiple services, the token exchange feature provided by Keycloak is a very useful solution. This technology allows an authenticated client to submit an existing token, which Keycloak verifies and exchanges for a new token with appropriate authority and target for the destination. This explicitly defines the trust relationships between services and controls the scope of authority, becoming a key foundation for enterprise security.

2. Integration Requirements and Adoption of Impersonation

During a recent project, there was a requirement to allow users who have already completed authentication on third-party platforms to access our services without a login window or additional login processing. The task was to implement a seamless UX to prevent users from logging in twice.

Although we tried to apply the standard Keycloak V2 engine, we faced technical constraints. The standard specification requires the actual login credential (original token) of the external service, but the partner could not share their token due to security policies and could only pass 'user unique ID (identifier)'.

Since we had to pass through with only identification information without an actual token, it was impossible to introduce the standard engine. Therefore, to meet the requirements without developing additional custom modules, we opted for an older specification (V1 Direct Naked Impersonation) method that allowed token issuance with only backend credentials and user ID strings. We established a structure that places a 'security proxy (Bridge Gateway)' in front to protect the internal infrastructure and receives tokens via a back channel to deliver to the screen.

3. Keycloak Configuration: Connecting Clients

To securely issue token exchange, explicit trust relationships must be defined between the requester and target clients in the Keycloak console.

  • Client for External Service (Requester): Set Client Authentication to On (Confidential) to hide the master secret key internally. To apply the older V1 mechanism, activate the older detailed management authority (FGAP:v1) specification at the server layer.

  • Client for Internal MSA (Target): Activate token-exchange in the Permissions menu of the client responsible for authorization and screen. Create a policy that maps to allow only the external proxy client to delegate and exchange tokens.

4. Backend Implementation: Token Request Specification

The proxy server (Spring Boot) validates requests from external systems and performs bridge code to securely call the Keycloak endpoint. The API payload specification according to the older V1 standard is as follows.

  • Endpoint URL: POST /realms/{realm-name}/protocol/openid-connect/token

  • Header Specification: Content-Type: application/x-www-form-urlencoded, Authorization: Basic [Base64(ID:Secret)]

Required Parameters for Token Issuance

Parameter Name

Configuration Values and Examples

Description

grant_type

urn:ietf:params:oauth:grant-type:token-exchange

Protocol Specification

requested_subject

user_internal_idx_01

Unique ID of the internal user for which the token is being issued

requested_token_type

urn:ietf:params:oauth:token-type:access_token

Explicit access token request

audience

internal-msa-core

Triggers downscoping by reducing unnecessary permissions

If the Keycloak validation is successful, the access_token is extracted from the response data. This token injects only the user's business internal roles (such as ROLE_USER) and the proxy loads it into the user’s browser after passing through the external service and performs a redirect.

5. Common errors and solutions

This is a handbook for handling three major runtime errors encountered during actual operation and deployment stages.

  • HTTP 404 Not Found error:Occurs when referencing an outdated document and including the /auth path in the endpoint address. The latest version has removed /auth from the default context path, so it should be omitted.

  • invalid_client error:Occurs when the token exchange spec-related option is not enabled in the settings of the proxy client sending the request, so the corresponding toggle switch in the console should be checked again.

  • 403 Forbidden / not_allowed error:Occurs when the client-to-client trust policy is lost. It must be verified whether the requesting client is registered as a policy subset in the Permissions menu of the Target client that is the final destination.

6. Limitations of the legacy (V1) method and practical compromises

The adoption of the legacy specification (V1 Direct Naked Impersonation) instead of the latest V2 standard engine in this project was a deliberate architectural choice to overcome the constraints of external integration environments.

Keycloak V2 standard engine requires submission of the original token to be exchanged as a mandatory specification. However, the external partner involved could not share user session tokens due to their own security policies, and there was a technical limitation that only allowed the provision of a 'unique user ID'. In a situation without the original token, the old V1 standard, which allows token issuance based solely on user ID, was the only practical alternative to meet the client's requirement of 'excluding additional login processing' in a timely manner without adding a separate encryption token generation system to the proxy server.

The potential risks of the old specification were offset by the multi-layered defense system of the infrastructure layer. The permissions of the server network (M2M) and the user interface network (UI) were strictly double isolated, and the validity period of the tokens exposed in the browser was limited to short-lived tokens of 3 to 5 minutes to control the risk of hijacking. Although there is a future task of migrating to the standard V2 system due to updates in the Keycloak engine, it was the most realistic engineering compromise to achieve business goals without touching the integration specifications with external parties within limited resources.

7. Conclusion

This project served as a re-confirmation of how challenging it is to secure both security and user convenience during B2B integration. The process of reviewing and seeking the best practical architecture under external infrastructure constraints itself became a significant asset. I hope this integration case serves as a practical reference for those considering a Keycloak-based authentication infrastructure in a microservices environment.

References

https://www.keycloak.org/securing-apps/token-exchange

oshua

Site footer