为什么我无法访问我的Controller,即使我已经在Spring Security中配置了antMatchers?

r6l8ljro  于 2023-04-30  发布在  Spring
关注(0)|答案(1)|浏览(273)

有人能帮帮我吗
TestController

@RestController
public class Test {
    @GetMapping("/test")
    public ResponseEntity<String > test(){
        System.out.println("Response body: " + "hello");
        return ResponseEntity.ok(" hello ");
    }
}

SecurityConfig

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

    public static final String[] EXCLUDE_PATH = {
            "/webjars/**",
            "/favicon.ico",
            "/captcha",
            "/user/login",
            "/user/logout",
            "/test"
    };
    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
    @Autowired
    private UserDetailsService customUserDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.cors().and()
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint).and()

                .authorizeRequests()
                .antMatchers(EXCLUDE_PATH).permitAll() 
                .anyRequest().authenticated()

             
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

        ;

        return http.build();
    }

    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        return webSecurity -> {
            webSecurity.ignoring().antMatchers(EXCLUDE_PATH);
        };
    }
}
b0zn9rqh

b0zn9rqh1#

令人困惑的是,当我创建一个新的Sping Boot 项目并迁移原始项目时,问题就解决了。这证实了我的安全配置没有问题,但我仍然对这种情况感到困惑。

相关问题