首页 > 解决方案 > 在anyRequest(多个antMatcher)之后无法配置antMatchers

问题描述

我正在尝试配置 Spring Security 并收到以下错误:

引起:java.lang.IllegalStateException: Can't configure antMatchers after anyRequest

这是我的SecurityConfig课:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

            auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
    }

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

        http
            .csrf().disable();
        http
            .httpBasic()
                .and()
            .authorizeRequests()
                .antMatchers("/rest/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .authorizeRequests()
                .antMatchers("/secure/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .permitAll();

        http
            .authorizeRequests()
                .antMatchers("/login").permitAll();
    }

    @Bean
    public BCryptPasswordEncoder encodePWD(){
        return new BCryptPasswordEncoder();
    }
}

我已经尝试过这里httpSecurityauthorizeRequests().anyRequest().authenticated()提到的电话,但仍然没有用......任何建议都会有所帮助。

标签: javaspringspring-security

解决方案


修改规则如下。.anyRequest().authenticated()只能使用一次。

    http
        .httpBasic()
            .and()
        .authorizeRequests()
            .antMatchers("/rest/**").permitAll()
            .and()
        .authorizeRequests()
            .antMatchers("/secure/**").hasAnyRole("ADMIN")
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .permitAll();

推荐阅读