javaspring-bootspring-securityvaadin23

Multiple Authentications in Spring Boot (parallel use of Vaadin and a REST API)


I want to run a Vaadin 23 frontend but also have a REST API in my application. I want to use Token-Based (JWT) authentication for the REST API and Standard form-based for the frontend. I have tested a lot of different configurations from examples in the Spring Security documentation and around the internet. The only configuration where both options get called upon initialization is this one:


@EnableWebSecurity
public class SecurityConfiguration extends VaadinWebSecurity {

    // ... other stuff here ...


    @Bean
    @Order(1)
    public SecurityFilterChain restFilterChain(HttpSecurity http) throws Exception {
        return http
                .cors().and().csrf().disable()
                .authorizeRequests().antMatchers("/api/login").anonymous().and()
                .authorizeRequests().antMatchers("/api/**").authenticated().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .addFilterBefore(authTokenFilter(), UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain frontendFilterChain(HttpSecurity http) throws Exception {
        super.configure(http);
        setLoginView(http, LoginView.class, LOGOUT_URL);

        return http.build();
    }
}

Both configuration blocks work, I have tried with either one being @Order(1) and the other being @Order(2). The configuration that gets @Order(1) is called on login and authentication works. But there is no fallback to @Order(2) regardless of how the other attempt ends (with .denyAll() or just "nothing"). What am I missing here?

Spring Version: 5.3.22

Spring Security Version: 5.7.3


Solution

  • for me this working well. Code on kotlin, but config code same as on java.

    override fun configure(http: HttpSecurity) {
    //        http.authorizeRequests().
    //        anonymousPostLeads(http)
            http
                .authorizeRequests().antMatchers("/api/login").anonymous().and()
                .authorizeRequests().antMatchers("/api/**").authenticated().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .addFilterBefore(authTokenFilter(), UsernamePasswordAuthenticationFilter::class.java)
    
    
            // Authorize access to /images/ without authentication
            http.authorizeRequests().antMatchers("/images/**").permitAll()
            super.configure(http)
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            setLoginView(http, LoginView::class.java, "/logout")
    
            http.cors().and().csrf().ignoringAntMatchers("/api/login", "/api/**")
        }