在 Spring Boot 和 Spring Security 应用程序中提供静态 Web 资源

新手上路,请多包涵

我正在尝试开发 Spring Boot Web 应用程序并使用 Spring 安全 Java 配置对其进行保护。

按照 Spring blog 中的建议将我的静态 Web 资源放在“ src/main/resources/public ”中后,我就可以获取静态资源了。即在浏览器中点击 https://localhost/test.html 会提供 html 内容。

问题

启用 Spring Security 后,点击静态资源 URL 需要身份验证。

我的相关 Spring Security Java 配置如下所示:-

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.
            authorizeRequests()
                .antMatchers("/","/public/**", "/resources/**","/resources/public/**")
                    .permitAll()
                .antMatchers("/google_oauth2_login").anonymous()
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/home")
                    .and()
                    .csrf().disable()
                    .logout()
                        .logoutSuccessUrl("/")
                        .logoutUrl("/logout") // POST only
                .and()
                    .requiresChannel()
                    .anyRequest().requiresSecure()
                .and()
                    .addFilterAfter(oAuth2ClientContextFilter(),ExceptionTranslationFilter.class)
                    .addFilterAfter(googleOAuth2Filter(),OAuth2ClientContextFilter.class)
                .userDetailsService(userService);
        // @formatter:on
    }

我应该如何配置 antMatchers 以允许放置在 src/main/resources/public 中的静态资源?

原文由 Kumar Sambhav 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 580
2 个回答

有几件事需要注意:

  • Ant 匹配器匹配请求路径,而不是文件系统上资源的路径。
  • 放置在 src/main/resources/public 中的资源将从应用程序的根目录提供。例如 src/main/resources/public/hello.jpg 将从 http://localhost:8080/hello.jpg 提供服务

这就是您当前的匹配器配置不允许访问静态资源的原因。要使 /resources/** 工作,您必须将资源放入 src/main/resources/public/resources 并在 http://localhost:8080/resources/your-resource 访问它们。

当您使用 Spring Boot 时,您可能需要考虑使用其默认值而不是添加额外的配置。 Spring Boot will, by default, permit access to /css/** , /js/** , /images/** , and /**/favicon.ico .例如,您可以拥有一个名为 src/main/resources/public/images/hello.jpg 的文件,并且无需添加任何额外配置,就可以在 http://localhost:8080/images/hello.jpg 访问它,而无需登录。您可以在 Web 方法安全冒烟测试,无需任何特殊配置即可访问 Bootstrap CSS 文件。

原文由 Andy Wilkinson 发布,翻译遵循 CC BY-SA 4.0 许可协议

  @Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/resources/**"); // #3
      }

忽略任何以“/resources/”开头的请求。这类似于在使用 XML 命名空间配置时配置 http@security=none。

原文由 RPaul 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进