One Comment

  1. Hi, cool article! It helped me a lot but one thing worth mentioning about the weird UsernamePasswordAuthenticationFilter: If you use it for custom authentication, i.e. outside formLogin etc., make sure to set its dependencies appropriately, like
    @Bean
    public UsernamePasswordAuthenticationFilter authenticationFilter(
    AuthenticationManager manager,
    SecurityContextRepository contextRepository,
    SessionAuthenticationStrategy sessionStrategy) {
    AuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler(“/signedIn”);

    final UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(manager);
    filter.setPostOnly(true);
    filter.setFilterProcessesUrl(“/login”);

    filter.setSecurityContextRepository(contextRepository);
    filter.setSessionAuthenticationStrategy(sessionStrategy);
    filter.setAuthenticationSuccessHandler(successHandler);
    return filter;
    }

    Also don’t forget to use the beans in the filter chain definition:
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
    .addFilter(authenticationFilter)
    .authorizeHttpRequests(auth ->
    auth.requestMatchers(“/actuator/**”).permitAll() // allow login and actuator
    .anyRequest().authenticated()) // secure all others
    .sessionManagement(session ->
    session.sessionAuthenticationStrategy(sessionAuthenticationStrategy)
    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
    .securityContext(securityContext ->
    securityContext.securityContextRepository(contextRepository)) // Store context in session
    .csrf(AbstractHttpConfigurer::disable); // needed for post request to succeed

    return http.build();
    }

    Hope this helps someone else as it took me quite some debugging time to figure that out.

Leave a Reply

Your email address will not be published. Required fields are marked *