轉自:https://blog.csdn.net/qq_34204490/article/details/110005404
Springboot + Spring-Security的踩坑記錄
問題描述:今天使用springboot整合springsecurity,出現靜態資源404的狀態
解決:
1.首先嘗試使用網上的方法繼承 WebSecurityConfigurerAdapter,然后重寫public void configure(WebSecurity web)
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(loadExcludePath());
}
private String[] loadExcludePath() {
return new String[]{
"/",
"/static/**",
"/templates/**",
"/img/**",
"/js/**",
"/css/**",
"/lib/**"
};
}
照道理說。這應該就可以了,然而我這里就是不能成功放行
2.於是我又重寫了方法 protected void configure(HttpSecurity http)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//關閉跨域限制
.csrf().disable()
.authorizeRequests()
//在此處放行
.antMatchers(loadExcludePath()).permitAll()
.anyRequest().authenticated()//其他的路徑都是登錄后即可訪問
.and()
.formLogin()
// .loginPage("/login")
// .loginProcessingUrl("/doLogin")
.successHandler(getAuthenticationSuccessHandler())
.failureHandler(getAuthenticationFailureHandler())
// .permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(getAccessDeniedHandler());
}
這里的重點是下面幾句(其他的配置可以忽略)
http
//關閉跨域限制
.csrf().disable()
.authorizeRequests()
//在此處放行
.antMatchers(loadExcludePath()).permitAll()
.anyRequest().authenticated()//其他的路徑都是登錄后即可訪問
然而盡管標紅的地方也進行了放行,可是依然失敗。
到目前為止,應該是已經沒問題了,畢竟兩個方法中都進行了放行,可是靜態資源依舊404
3.最終發現是跨域配置和springsecurity產生了沖突
也就是我項目中在其他位置配置了跨域的內容,如下
@Configuration
public class CORSConfiguration extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders(
"access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
.allowCredentials(true)
.maxAge(3600);
super.addCorsMappings(registry);
}
}
把 CORSConfiguration 注釋掉,最終問題解決
————————————————
版權聲明:本文為CSDN博主「@小小白!」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_34204490/article/details/110005404