Spring云网关-拦截对Keycloak IDP的幕后请求/响应

brc7rcf0  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(139)

我们正在实现一个Spring Cloud Gateway应用程序(使用Webflux),该应用程序通过Keycloak中介OAuth2身份验证。
SCG检查Spring会话是否处于活动状态:如果没有,则重定向到Keycloak登录页面并处理来自IDP的响应。此过程由框架本身即时执行。
我们需要拦截IDP Keycloak响应,以便从响应负载中检索字段。
你有什么建议,将帮助我们完成这一行为?
谢谢你!

mcvgt66p

mcvgt66p1#

您可以实现ServerAuthenticationSuccessHandler

@Component
public class AuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {

    private ServerRedirectStrategy redirectStrategy;

    public AuthenticationSuccessHandler(AuthenticationService authenticationService) {
        redirectStrategy = new DefaultServerRedirectStrategy();

    }

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        if(authentication instanceof OAuth2AuthenticationToken) {
            //Your logic here to retrieve oauth2 user info
        }
        ServerWebExchange exchange = webFilterExchange.getExchange();
        URI location = URI.create(httpRequest.getURI().getHost());
        return redirectStrategy.sendRedirect(exchange, location);
    }

}

并更新您的安全配置以包括成功处理程序:

@Configuration
public class SecurityConfiguration {

    private AuthenticationSuccessHandler authSuccessHandler;

    public SecurityConfiguration(AuthenticationSuccessHandler authSuccessHandler) {
        this.authSuccessHandler = authSuccessHandler;
    }

    @Bean
    SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http
            .authorizeExchange(exchange -> exchange
            //other security configs
                    .anyExchange().authenticated()
                    .and()
                    .oauth2Login(oauth2 -> oauth2
                            .authenticationSuccessHandler(authSuccessHandler)

                    );

        return http.build();
    }
}

相关问题