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

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


按照Spring博客中的建议,将我的静态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中?


千巷猫影
浏览 756回答 3
3回答

斯蒂芬大帝

有几件事要注意: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时,您可能需要考虑使用其默认值,而不是添加额外的配置。春天开机后,默认,允许访问/css/**,/js/**,/images/**,和/**/favicon.ico。例如,您可以拥有一个名为的文件src/main/resources/public/images/hello.jpg,而无需添加任何额外的配置,http://localhost:8080/images/hello.jpg无需登录即可访问该文件。您可以在允许对Bootstrap CSS文件进行访问的Web方法安全性示例中看到此操作。无需任何特殊配置。

莫回无

 @Override      public void configure(WebSecurity web) throws Exception {        web          .ignoring()             .antMatchers("/resources/**"); // #3      }忽略任何以“ / resources /”开头的请求。这与使用XML名称空间配置时配置http @ security = none相似。
打开App,查看更多内容
随时随地看视频慕课网APP