【问题标题】:Static web resources in Spring Boot + Spring Security + ThymeleafSpring Boot + Spring Security + Thymeleaf 中的静态 Web 资源
【发布时间】:2017-11-02 10:15:56
【问题描述】:

我正在尝试让 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()

它从来没有奏效。解决办法是什么? 附言。我看过一个声明,Spring Boot + Spring Security 默认允许这种资源内访问,但它不允许。

【问题讨论】:

    标签: java spring-boot spring-security


    【解决方案1】:

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

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

    而不是

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

    【讨论】:

      【解决方案2】:

      在那里查看我的答案: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 安全性,因为它与它无关,即您的第一个代码示例似乎是正确的。

      【讨论】: