首页 > 解决方案 > 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();
    }
}

我想onAuthenticationSuccess在 KeyCloak 将我重定向到实际资源之前添加一些自定义代码。我尝试使用AuthenticationSuccessHandlerand do实现一个自定义类formLogin().successHandler(...)。这没有用。我怎样才能得到这个工作?

标签: spring-bootspring-securitykeycloak

解决方案


如果您仍然喜欢使用 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());
}

推荐阅读