【发布时间】:2022-01-26 17:53:49
【问题描述】:
我在我的应用程序中使用 Spring Boot KeyCloak 来连接 KeyCloak。但是我有一个没有被调用的自定义成功处理程序。我不确定为什么。这是我的代码:
SecurityConfiguration.java:
@KeycloakConfiguration
public class SecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Bean
@Primary
@Override
protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {
KeycloakAuthenticationProcessingFilter filter = new KeycloakAuthenticationProcessingFilter(authenticationManagerBean());
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
filter.setAuthenticationSuccessHandler(successHandler());
filter.setAuthenticationFailureHandler(failureHandler());
return filter;
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf().disable().authorizeRequests()
.antMatchers("/**").authenticated();
}
@NotNull
@Bean
public KeyCloakAuthSuccessHandler successHandler() {
return new KeyCloakAuthSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler());
}
@NotNull
@Bean
public KeyCloakAuthFailureHandler failureHandler() {
return new KeyCloakAuthFailureHandler();
}
}
在我的KeyCloakAuthSuccessHandler.java 中,我有:
@Slf4j
public class KeyCloakAuthSuccessHandler extends KeycloakAuthenticationSuccessHandler {
@Autowired
ObjectMapper mapper;
public KeyCloakAuthSuccessHandler(AuthenticationSuccessHandler fallback) {
super(fallback);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
log.error("inside success handler");
if (authentication.getPrincipal() instanceof KeycloakPrincipal) {
AccessToken token = ((KeycloakPrincipal<?>) authentication.getPrincipal()).getKeycloakSecurityContext().getToken();
// do other stuff
}
}
}
上面的代码没有调用成功处理程序,但是类似的失败处理程序正在工作并被调用。
【问题讨论】:
-
为什么要用@Slf4j 注释类?
-
用于在我的成功处理程序中记录内容
-
@mifol68042 您是否尝试过一次又一次地不传递承载/基本(无论配置哪个)标头进行测试?即使在这两种情况下,它都不会通过成功处理程序吗?因为代码看起来很正确。
-