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

KeyCloak Spring Boot - Add custom code on auth success

我正在使用 KeyCloak 与 Spring Boot 集成,如 this 指南中所述。我的安全配置如下:

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

我想在 KeyCloak 将我重定向到实际资源之前为 onAuthenticationSuccess 添加一些自定义代码。我尝试使用 AuthenticationSuccessHandler 实现自定义 class 并执行 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());
}