我们正在实现一个Spring Cloud Gateway应用程序(使用Webflux(,该应用程序正在使用Keycloft中介OAuth2身份验证。
SCG检查Spring会话是否处于活动状态:如果不是,则重定向到Keycapture登录页面并处理来自IDP的响应。这个过程是由框架本身开箱即用地执行的。
我们的需求是拦截IDP密钥斗篷响应,以便从响应有效载荷中检索字段。
你有什么建议可以帮助我们完成这种行为吗?
谢谢!
您可以实现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();
}
}