Combining basic authentication and form login for the same REST Api

One might try with the only ConfigurationAdapter class rather than two, e.g.:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()
            .and()
        .csrf()
            .disable()
        .httpBasic()
            .and()
        .authorizeRequests()
            .antMatchers("/login/**").permitAll()
            .anyRequest().authenticated()
        .and()
            .formLogin()
    ;
}

Ref.: https://medium.com/@haytambenayed/basic-authentication-and-form-based-authentication-using-spring-security-ed79951dbb2e


You can achieve this easily by using multiple http configuration as below, this code only explains multiple http configuration. I am assuming that you are well aware of the other essential configurations related to spring security e.g authenticationManger etc.

    @EnableWebSecurity
    public class MultiHttpSecurityCustomConfig {
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password")
                    .roles("USER", "ADMIN");
        }

        @Configuration
        @Order(1)
        public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
            protected void configure(HttpSecurity http) throws Exception {
                http.antMatcher("/api/**").authorizeRequests().anyRequest().hasRole("ADMIN").and().httpBasic();
            }
        }

        @Configuration
        public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests().anyRequest().authenticated().and().formLogin();
            }


   }
}

Please refer spring security official link: Multiple HttpSecurity

I will also reccomend you to check out Secure REST Services with Spring Security

Feel free to comment if you encounter any problem!