KeyCloak Spring Boot -在授权成功时添加自定义代码



我在本指南中使用KeyCloak与Spring Boot的集成。我有我的安全配置如下:

class KeycloakSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().antMatchers("/**").authenticated()
.anyRequest().permitAll();
}
}

我想在KeyCloak将我重定向到实际资源之前为onAuthenticationSuccess添加一些自定义代码。我尝试实现一个自定义类与AuthenticationSuccessHandler和做formLogin().successHandler(...)。这行不通。我怎样才能让它工作??

如果您仍然喜欢使用Spring Boot KeyCloak,那么这样做就可以了。

public class KeyCloakAuthSuccessHandler extends KeycloakAuthenticationSuccessHandler {

public KeyCloakAuthSuccessHandler(AuthenticationSuccessHandler fallback) {
super(fallback);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
if (authentication.getPrincipal() instanceof KeycloakPrincipal) {
AccessToken token = ((KeycloakPrincipal<?>) authentication.getPrincipal()).getKeycloakSecurityContext().getToken();
}
super.onAuthenticationSuccess(request, response, authentication);
}
}

并且在扩展KeyCloakWebSecurityConfigurerAdapter的安全配置或类似文件中执行以下操作:

@Bean
@Override
protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {
KeycloakAuthenticationProcessingFilter filter = new KeycloakAuthenticationProcessingFilter(authenticationManagerBean());
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
filter.setAuthenticationSuccessHandler(successHandler());
return filter;
}

@NotNull
@Bean
public KeyCloakAuthSuccessHandler successHandler() {
return new KeyCloakAuthSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler());
}

最新更新