简体   繁体   中英

Mix HttpBasic and FormLogin in Spring Security with Spring-boot-starter

I use spring-boot-starter 0.5.0.M6 with spring security to build my application which contains:

  1. "/admin/ "**: should be accessible to anyone have role ADMIN, form-based login
  2. "/api/ "**: should be accessible to anyone have role API, http basic login

My first attempt was:

@Override
protected void configure(HttpSecurity http) throws Exception {
      http
        .authorizeRequests()
          .antMatchers("/resources/**").permitAll()
          .antMatchers("/admin/**").hasRole("ADMIN")
        .and()
          .formLogin()
          .defaultSuccessUrl("/admin/home")
          .loginPage("/login")
          .permitAll()
        .and()
          .logout()
          .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
          .permitAll();  
      http
        .authorizeRequests()
          .antMatchers("/api/**").hasRole("API")
        .and()
          .httpBasic();
}

With this approach:

  1. all the "/admin/ " and "/api/ " can authentication use both basic & form-based login. This is not a critical issue.
  2. when any security issue occurred, eg: authentication failed, or authorization failed, the login form is shown. This is a critical issue, I want if /api/** get authentication failed or authorization failed, it show the basic authentication popup with 401/403 status code.

Then I try with the solution from https://github.com/spring-projects/spring-security-javaconfig/blob/master/samples-web.md#sample-multi-http-web-configuration , but I only able to secure either /api/** or /admin/** but not both, depends on which one I annotated with @Order .

Please give me a hand.

Thanks much

For your api part, use the following. Note the first ant matcher that limits the scope of what is filtered by this security configuration. That was the part I did not understand at first from your reference.

@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        // the ant matcher is what limits the scope of this configuration.
        http.antMatcher("/api/**").authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .and().httpBasic().realmName("Sourcing API");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM