如何配置Spring Security 6以忽略静态资源文件夹?

mw3dktmi  于 2023-10-16  发布在  Spring
关注(0)|答案(2)|浏览(382)

我将我的公共Web资源(CSS,JS)存储在“静态”文件夹中,路径如下:“java/com/myapp/resources/static/**”。这里我的配置类:
SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated())
                .formLogin(form -> form
                        .loginPage("/login")
                        .permitAll());
        return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() throws Exception {
        return (web) -> web.ignoring().antMatchers("/resources/static/**");
    }

}

以及ResourceConfig.java

@Configuration
public class ResourceConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
        registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/");
    }
    
}

它在Spring Security版本5.x.x上工作,但在Spring Security的当前版本(6.0.3)中,方法'antMatchers(String)'对于类型'WebSecurity. IgnoredRequestConfigurer'未定义,所以我不能再以同样的方式配置它。
我读了这个文档(https://docs.spring.io/spring-security/reference/5.8/migration/servlet/config.html#use-new-requestmatchers),其中声明我可以用“requestMatchers”替换弃用的“antMatchers”方法,如下所示:

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().requestMatchers("/resources/static/**");
}

然而,即使在进行了此更改后,我的CSS文件仍然丢失。所以,我想问:如何配置Spring Security 6以忽略静态资源文件夹?谢谢

xiozqbni

xiozqbni1#

它更安全,因为即使使用静态资源,编写安全的头文件也很重要,如果请求被忽略,Spring Security就不能这样做。
在过去,这带来了性能权衡,因为Spring Security在每个请求上都会咨询会话。然而,从Spring Security 6开始,除非授权规则要求,否则会话不再被ping。因为现在已经解决了性能影响,Spring Security建议至少对所有请求使用permitAll。
https://docs.spring.io/spring-security/reference/6.1-SNAPSHOT/servlet/authorization/authorize-http-requests.html#favor-permitall

w6lpcovy

w6lpcovy2#

在requestMatchers中添加新的AntPathRequestMatcher(“YOUR PATH”):

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.csrf().disable()
                .authorizeHttpRequests().
                       requestMatchers(new AntPathRequestMatcher("/images/**")).permitAll()
                    .anyRequest()
                    .authenticated()
                    .and()
                .build();
    }

相关问题