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

问题描述 投票:0回答:2

我想为我的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();
}
...
authentication spring-boot
2个回答
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();
    }
}

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


0
投票

WebSecurityConfigurerAdapter 现已弃用(Spring Security 6.0 及更高版本) 所以我们可以将上面的代码改写为

@Configuration
@EnableWebSecurity
public class SecurityConfig{
public SecurityFilterChain 
filterchain(HttpSecurity http) throws 
Exception {

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

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class BasicSecurityConfig {

public SecurityFilterchain 
filterchain(HttpSecurity http) 
throws 
Exception {
    http.csrf().disable();
    http.requestMatcher("/api/**")
        .authorizeHttpRequests()
        .anyRequest()
        .authenticated()
        .httpBasic();
         }
     } 
© www.soinside.com 2019 - 2024. All rights reserved.