i have a customized form login, which worked using WebSecurityConfigurerAdapter. but after i tried to migrate it using spring security filter chain, i have the problem that my security context forgets the authentication token after successful login and a subsequent redirect.
my config is as follows:
@Configuration
@EnableWebSecurity
public class FormLoginConfig {
@Autowired
private MyUserDetailsService userDetailsService;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.requestCache(c -> c.requestCache(new CustomRequestCache()))
.addFilterAt(getFormAuthFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeHttpRequests(a -> a.requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()
.anyRequest().authenticated()
)
.formLogin(l -> l.loginPage("/login").permitAll())
.headers(h -> h.frameOptions(FrameOptionsConfig::sameOrigin));
return http.build();
}
@Bean
public AuthenticationSuccessHandler successHandler() {
return new MyLoginSuccessHandler();
}
@Bean
public MyAuthenticationFilter getFormAuthFilter() throws Exception {
MyAuthenticationFilter filter = new MyAuthenticationFilter();
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
filter.setAuthenticationManager(formUserAuthManager());
filter.setAuthenticationSuccessHandler(successHandler());
return filter;
}
AuthenticationManager formUserAuthManager() {
return authentication -> authProvider().authenticate(authentication);
}
public AuthenticationProvider authProvider() {
return new MyAuthenticationProvider(passwordEncoder(), userDetailsService);
}
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
the authentication itself works, i can login and the success handler is called with a valid security context. after the redirect to the secured area the context only has the anonymous user left and i return back to the login form.
i was reading about the same problem from other users but, like in this one, the issue seemed to be the session management, which i didn't use in my config.
now i'm out of ideas and hope someone else can see the issue.