[英]Not able to map static resources i.e. JS, CSS, images in spring MVC
[英]Spring Security 4 with Spring Boot: static resource (i.e. css, js, img) 404 issue
我正在使用带有Spring Security的Spring Boot来创建启用了SSL(手动创建的SSL文件)的Web应用程序。 一切工作正常,但是,每当我尝试访问任何静态资源(如CSS或js文件)时,它都无法找到这些文件并显示以下错误:
由于MIME类型不匹配(X-Content-Type-Options:nosniff),“ https:// localhost:8443 / css / lib / index.css ”中的资源被阻止。
这不仅发生在登录页面上,而且也在其他页面上发生。 成功登录后,我也收到此错误。
以下是我的安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**"/*, "/js/**", "/img/**", "/error"*/).permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.defaultSuccessUrl("/home", true)
.successHandler(authSuccessHandler)
.and()
.headers()
.frameOptions().sameOrigin()
.httpStrictTransportSecurity().disable()
.and()
.logout().addLogoutHandler(new LogoutHandler() {
@Override
public void logout(HttpServletRequest request,HttpServletResponse response, Authentication authentication) {
request.getSession().invalidate();
}
})
.logoutUrl("/logout").permitAll().logoutSuccessUrl("/login")
.invalidateHttpSession(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.deleteCookies("JSESSIONID")
.and()
.sessionManagement().maximumSessions(1);
}
CSS文件位于以下路径中:
src/main/resources/public/css/lib/index.csss
我正在使用Freemarker,下面是如何调用此CSS文件的方法:
<link rel="stylesheet" href="/css/lib/index.css" type="text/css" media="screen" charset="utf-8"/>
我在这里做错了什么?
如果您没有使用Boot进行WebMvc的自动配置,而是拥有一个带有注释@EnableWebMvc的配置类,该类扩展了WebMvcConfigurerAdapter
然后覆盖以下方法,它为/ public / **添加所需的位置
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/public/**")
.addResourceLocations("/public/");
在“安全配置”文件中,添加以下内容:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/public/**");
}
}
这将确保/ public / **被排除在安全预览之外
尝试完全忽略并从处理中排除这些资源:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**","/js/**","/img/**","/error/**");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.