简体   繁体   English

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

[英]Static web resources in Spring Boot + Spring Security + Thymeleaf

I'm trying to make Spring Security permit access to static resources to all users, but for now nothing works. 我试图使Spring Security允​​许所有用户访问静态资源,但目前没有任何效果。 When I used jsp in previous project, the solution was simple: 当我在上一个项目中使用jsp时,解决方案很简单:

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

Static folder was placed inside webapp folder which was the root folder and was easily detected by Spring Security. 静态文件夹放置在webapp文件夹内,该文件夹是根文件夹,并且可以通过Spring Security轻松检测到。 Now, because of Thymeleaf, there is no webapp folder and all the static folders are placed into src/main/resources. 现在,由于Thymeleaf,没有webapp文件夹,所有静态文件夹都放置在src / main / resources中。 I have no idea, how to create antMatcher for something that is inside resources folder... I tried that: 我不知道如何为资源文件夹中的内容创建antMatcher ...我尝试过:

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

It never worked. 它从来没有奏效。 What is the solution? 解决办法是什么? ps. PS。 I have seen a statement that Spring Boot + Spring Security allows this intra-resources access by default, but it does not. 我已经看到一条声明,默认情况下,Spring Boot + Spring Security允​​许此资源内部访问,但事实并非如此。

The solution is found. 找到解决方案。 For my folder structure src/main/resource/static/css I should have used 对于我的文件夹结构src / main / resource / static / css,我应该使用

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

instead of 代替

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

Check my answer there: Spring boot mapping static html 在那检查我的答案: Spring Boot映射静态html

Basically you have to add resource handlers by extending WebMvcConfigurerAdapter to map http://yoursite/static_url_prefix to your static_app_dir directory in your resources directory. 基本上,您必须通过扩展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);
}

This will intercept all request coming to http://yoursite/static_url_prefix and return results from classpath://static_app_dir in your jar file or from /resources/static_app_dir when running application from your IDE. 当您从IDE中运行应用程序时,这将拦截来自http://您的网站/ static_url_prefix的所有请求,并从jar文件中的classpath:// static_app_dir或/ resources / static_app_dir返回结果。

Spring security can be configured as before as it has nothing to do with it ie your first code example seems correct. 可以像以前一样配置Spring安全性,因为它与它无关,即您的第一个代码示例似乎是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM