How to use multiple login pages one for admin and the other one for user

Both security filter chains are not restricted (default is /**).

Spring Security 6

You have to restrict the first one with securityMatcher, see Spring Security Reference:

Multiple HttpSecurity Instances

We can configure multiple HttpSecurity instances just as we can have multiple <http> blocks in XML. The key is to register multiple SecurityFilterChain @Beans. The following example has a different configuration for URL’s that start with /api/.

@Configuration
@EnableWebSecurity
public class MultiHttpSecurityConfig {
  @Bean                                                             
  public UserDetailsService userDetailsService() throws Exception {
      // ensure the passwords are encoded properly
      UserBuilder users = User.withDefaultPasswordEncoder();
      InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
      manager.createUser(users.username("user").password("password").roles("USER").build());
      manager.createUser(users.username("admin").password("password").roles("USER","ADMIN").build());
      return manager;
  }

  @Bean
  @Order(1)                                                        
  public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
      http
          .securityMatcher("/api/**")                                   
          .authorizeHttpRequests(authorize -> authorize
              .anyRequest().hasRole("ADMIN")
          )
          .httpBasic(withDefaults());
      return http.build();
  }

  @Bean                                                            
  public SecurityFilterChain formLoginFilterChain(HttpSecurity http) throws Exception {
      http
          .authorizeHttpRequests(authorize -> authorize
              .anyRequest().authenticated()
          )
          .formLogin(withDefaults());
      return http.build();
  }
}
  1. Configure Authentication as usual.
  2. Create an instance of SecurityFilterChain that contains @Order to specify which SecurityFilterChain should be considered first.
  3. The http.securityMatcher states that this HttpSecurity is applicable only to URLs that start with /api/.
  4. Create another instance of SecurityFilterChain. If the URL does not start with /api/, this configuration is used. This configuration is considered after apiFilterChain, since it has an @Order value after 1 (no @Order defaults to last).

Leave a Comment