Spring Boot + Spring Security + Thymeleaf中的静态Web资源

时间:2017-06-01 10:05:24

标签: java spring-boot spring-security

我正在尝试让Spring Security允​​许所有用户访问静态资源,但现在没有任何作用。 当我在之前的项目中使用jsp时,解决方案很简单:

http
                .authorizeRequests()
                .antMatchers("/static/**").permitAll()
                .anyRequest().authenticated()

静态文件夹放在webapp文件夹中,该文件夹是根文件夹,很容易被Spring Security检测到。现在,由于Thymeleaf,没有webapp文件夹,所有静态文件夹都放在src / main / resources中。我不知道,如何为资源文件夹内的东西创建antMatcher ...我试过了:

http
                .authorizeRequests()
                .antMatchers("resources:/static/**").permitAll()
                .anyRequest().authenticated()

它从未奏效。解决办法是什么? PS。我已经看到一个声明,Spring Boot + Spring Security默认允许这种资源内访问,但事实并非如此。

2 个答案:

答案 0 :(得分:1)

找到解决方案。对于我的文件夹结构src / main / resource / static / css我应该使用

.antMatchers("/css/**").permitAll()

而不是

.antMatchers("/static/**").permitAll()

答案 1 :(得分:-1)

在那里检查我的答案:Spring boot mapping static html

基本上,您必须通过扩展WebMvcConfigurerAdapter以将http://yoursite/static_url_prefix映射到资源目录中的static_app_dir目录来添加资源处理程序。

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

这将拦截来自http://yoursite/static_url_prefix的所有请求,并从jar文件中的classpath:// static_app_dir返回结果,或者从IDE运行应用程序时从/ resources / static_app_dir返回结果。

可以像以前一样配置Spring安全性,因为它与它无关,即你的第一个代码示例似乎是正确的。

相关问题