springkeycloakspring-webflux

How to access spring websession when creating a bean in webflux


i am using keycloak in my application and trying to configure the back-channel-logout url dynamically by sending the two required parameters client_session_state & client_session_host when doing the access token call.

To achive this, my idea is to override the bean ReactiveOAuth2AccessTokenResponseClient by adding my custom ParameterConverter to set these two client_session_state & client_session_host parameters.

    @Bean
    public ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> reactiveOAuth2AccessTokenResponseClient() {
        WebClientReactiveAuthorizationCodeTokenResponseClient accessTokenResponseClient = new WebClientReactiveAuthorizationCodeTokenResponseClient();
        accessTokenResponseClient.addParametersConverter(authorizationGrantRequest -> {
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("client_session_state", RequestContextHolder.currentRequestAttributes().getSessionId());
            params.add("client_session_host", "http://localhost:8080");
            return params;
        });
        return accessTokenResponseClient;
    }

The problem here is that i could not use RequestContextHolder inside webflux as it will bound to the local thread which agains the reactive concept. I will get an exception when using it here to read the session id.

Can anyone please give a hint how can i get the current web sesison here by not using the RequestContextHolder. I would appreciate any suggessions. Thank you!


Solution

  • Answering myself, i found the way to read the websession from the context view:

    Mono.deferContextual(Mono::just)
                    .filter(contextView -> contextView.hasKey(ServerWebExchange.class))
                    .map(contextView -> contextView.get(ServerWebExchange.class))
                    .flatMap(ServerWebExchange::getSession)
                    .flatMap(webSession -> ...do logic)