经常有小伙伴说自己配置了SpringScurity后,访问静态资源时出现各种各样的问题,比如访问html时前端页面出现了MIME 类型(“text/html”)不匹配(X-Content-Type-Options: nosniff)的报错,报错码是302,http中302的表示是暂时性转移(Temporarily Moved ),意思是访问的内容被重定向了,这种情况十有八九都是被后端的过滤器给拦截了,于是在这里统一对SpringScurity配置静态资源讲解下,也算是给自己做做笔记。
首先要在项目中设置静态资源的目录,比如我的html放在templates文件夹下而css和js放在了static文件夹:
相应的就要设置静态资源的路径为:
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").
addResourceLocations("classpath:/templates/","classpath:/static/");
}
}
上面的设置只是表示你在项目中访问静态资源时可以不用带templates和static的路径了,接下来还要配置SpringScurity的静态请求不拦截,两种方法:
方法一:
@Configuration
public class SpringSecurrityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
// 使用 BCrypt 加密
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 定义当需要用户登录时候,转到的登录页面。
.loginPage("/login.html") // 设置登录页面
.loginProcessingUrl("/user/login") // 自定义的登录接口
.and()
.authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
.antMatchers("/login.html","/css/**").permitAll() // 设置所有人都可以访问登录页面以及css资源
.anyRequest() // 任何请求,登录后可以访问
.authenticated()
.and()
.csrf().disable(); // 关闭csrf防护
}
}
方法二:
@Configuration
public class SpringSecurrityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
// 使用 BCrypt 加密
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 定义当需要用户登录时候,转到的登录页面。
.loginPage("/login.html") // 设置登录页面
.loginProcessingUrl("/user/login") // 自定义的登录接口
.and()
.authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
.antMatchers("/login.html").permitAll() // 设置所有人都可以访问登录页面
.anyRequest() // 任何请求,登录后可以访问
.authenticated()
.and()
.csrf().disable(); // 关闭csrf防护
}
@Override
public void configure(WebSecurity web) throws Exception {
// 设置静态资源不要拦截
web.ignoring().antMatchers("/css/**");
}
}