在同一个 springboot 应用程序上实现 http basic 和 forms 登录

Dan*_*elC 1 authentication spring-boot

我想为我的 springboot 应用程序的路径“/api/”实现 http 基本身份验证,并为路径“/”和“/admin”实现表单身份验证。

这是我当前的java配置代码,但它不起作用,有什么想法吗?=) 此代码使所有站点都使用 http basic 进行保护,而不仅仅是“/api”。我在 stackoverflow 中发现了一些问题,但它们似乎没有解决我的问题:

public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource datasource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**").authenticated().and()
                .httpBasic();
        http.authorizeRequests()
                .antMatchers("/**").authenticated()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .and()
                .formLogin().loginPage("/login").permitAll()
                .defaultSuccessUrl("/inicio");
        http.logout().permitAll();

        http.csrf().disable();
    }

    http.csrf().disable();
}
...
Run Code Online (Sandbox Code Playgroud)

Y.M*_*.M. 5

我遇到了同样的问题,必须将基本身份验证和表单身份验证分开。

@Configuration
@EnableWebSecurity
public class FormSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests() //
            .antMatchers("/**").authenticated() //
            .antMatchers("/admin/**").hasRole("ADMIN") //
            .and() //
            .formLogin().loginPage("/login").defaultSuccessUrl("/inicio").permitAll() //
            .and() //
            .logout();
    }
}

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.antMatcher("/api/**") //
            .authorizeRequests().anyRequest().authenticated() //
            .and() //
            .httpBasic();
    }
}
Run Code Online (Sandbox Code Playgroud)

https://docs.spring.io/spring-security/reference/servlet/configuration/java.html#_multiple_httpsecurity_instances