I’m working in security on my spring boot 3 application, calling the keycloak logout endpoint is working fine, and my session in keycloak is being finished. But when I call my backend with the token that is supposed to be invalid, spring still granted access, so I tried created a custom logout handler, like this:
But how to get the id_token_hint? What’s the right way to log out spring boot and keycloak session?
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.requestMatchers(HttpMethod.GET, "/test/anonymous", "/test/anonymous/**")
.permitAll()
.requestMatchers(HttpMethod.GET, "/test/admin", "/test/admin/**")
.hasRole(ADMIN)
.requestMatchers(HttpMethod.GET, "/test/user")
.hasAnyRole(ADMIN, USER)
.requestMatchers(HttpMethod.GET, "/test/logout", "/test/logout/**")
.hasAnyRole(ADMIN, USER)
.anyRequest()
.authenticated()
.and()
.logout()
.logoutSuccessHandler(KeycloakLogoutHandler)
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSIONID")
.and()
.oauth2Login();
http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthConverter);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
}
@Override
public void onLogoutSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication
) throws IOException, ServletException {
String state = request.getParameter(STATE);
try {
response.sendRedirect("http://localhost:8080/realms/7vis/protocol/openid-connect/logout?id_token_hint=" +
authentication.);
} catch (IOException e) {
e.printStackTrace();
}
}
}