問題描述
在使用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下新建一個文件夾,然後在上述方法中指定跳過攔截的文件路徑即可。