问题描述
在使用Spring boot + Spring Security整合的时候,Spring Security对登陆进行了响应的处理操作,但是在进入登陆页的时候,出现页面报错,页面布局全部错乱的问题,查看原因发现是CSS与JS等静态文件没有被加载成功导致
问题原因
Spring Security默认会对静态文件进行拦截,这个问题在Spring MVC中也出现过,Spring MVC的解决办法是在配置文件中加入静态资源的引用配置,但是Spring boot + Spring Security整合中采用全注解方式,没有配置文件,因此需要进行如下改动:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启security注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//允许所有用户访问"/"和"/home"
http.authorizeRequests()
.antMatchers("/home").permitAll()
//其他地址的访问均需验证权限
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login") //指定登录页是"/login"
.defaultSuccessUrl("/list") //登录成功后默认跳转到"list"
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/home") //退出登录后的默认url是"/home"
.permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
//解决静态资源被拦截的问题
web.ignoring().antMatchers("/global/**");
}
}
Spring boot的默认静态资源放置位置是在resource/static下,可以在static下新建一个文件夹,然后在上述方法中指定跳过拦截的文件路径即可。