多模式spring boot中的多个WebsecurityConfigureAdapter

cotxawn7  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(385)

我正在尝试为我的项目设置多个websecurityconfigureradapter,其中spring引导执行器api使用basic auth进行安全保护,所有其他端点使用jwtauthentication进行身份验证。我只是不能让它一起工作,只有配置与较低的顺序工作。我使用的是springboot2.1.5.release
带有jwt验证器的安全配置一

@Order(1)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private static final String[] AUTH_WHITELIST = {
        "/docs/**",
        "/csrf/**",
        "/webjars/**",
        "/**swagger**/**",
        "/swagger-resources",
        "/swagger-resources/**",
        "/v2/api-docs"
};

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers(AUTH_WHITELIST).permitAll()
            .antMatchers("/abc/**", "/abc/pdf/**").hasAuthority("ABC")
            .antMatchers("/ddd/**").hasAuthority("DDD")
            .and()
            .csrf().disable()
            .oauth2ResourceServer().jwt().jwtAuthenticationConverter(new GrantedAuthoritiesExtractor());
   }
}

带有用户名/密码的基本身份验证配置

@Order(2)
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

/*    @Bean
public UserDetailsService userDetailsService(final PasswordEncoder encoder) {
    final InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    manager.createUser(
            User
                    .withUsername("user1")
                    .password(encoder.encode("password"))
                    .roles("ADMIN")
                    .build()
    );
    return manager;
}

@Bean PasswordEncoder encoder(){
    return new BCryptPasswordEncoder();
}*/

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/actuator/**").hasRole("ADMIN")
            .and()
            .httpBasic();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user1").password("password").authorities("ADMIN");
  }
}

我已经努力使它工作了很多天,但不能使他们两个一起工作。如果我交换顺序,只有basic auth工作,jwt auth管理器不工作。
我问了很多问题,比如
[spring boot security-多网站安全配置适配器]
[在spring boot中有多个websecurityconfigureradapter的问题]
[https://github.com/spring-projects/spring-security/issues/5593][1]
[https://www.baeldung.com/spring-security-multiple-entry-points][1]
似乎什么都没用,这是 Spring 的已知问题吗?

eanckbw9

eanckbw91#

使用多个 WebsecurityConfigurerAdapter ,您需要使用 RequestMatcher .
在您的情况下,您可以为 ActuatorSecurityConfig 仅限于执行器端点:

@Order(-1)
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers().antMatchers("/actuator/**")
                .and()
                .authorizeRequests().anyRequest().hasRole("ADMIN")
                .and()
                .httpBasic();
    }
}

相关问题