我正在尝试开发 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 许可协议
有几件事需要注意:
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 文件。