【问题标题】:Spring Cloud Gateway - Intercept under hood request/response to Keycloak IDPSpring Cloud Gateway - 拦截对 Keycloak IDP 的请求/响应
【发布时间】:2022-10-24 08:52:55
【问题描述】:
我们正在实现一个 Spring Cloud Gateway 应用程序(使用 Webflux),它使用 Keycloak 调解 OAuth2 身份验证。
SCG 检查 Spring Session 是否处于活动状态:如果没有,则重定向到 Keycloak 登录页面并处理来自 IDP 的响应。此过程由框架本身开箱即用地执行。
我们需要拦截 IDP Keycloak 响应,以便从响应负载中检索字段。
您有什么建议可以帮助我们完成这种行为吗?
谢谢!
【问题讨论】:
标签:
spring
keycloak
spring-webflux
spring-cloud-gateway
spring-session
【解决方案1】:
你可以实现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();
}
}