SpringSecurity跨域

 

在用SpringSecurity有個問題頭疼的半天,也可能是對SpringSecurity的不熟悉導致,在此貼一下怎麼去解決的。

項目架構是微服務架構,那自然是前後端分離撒,在前端進行Ajax請求時出現了跨域問題

感覺不是大問題喃,就算我不會解決,網上解決跨域的問題不是一堆麼。

我就注入了一個配置類,如下:

@Configuration
public class CorsConfig {
  private CorsConfiguration buildConfig() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.addAllowedOrigin("*"); // 1允許任何域名使用
    corsConfiguration.addAllowedHeader("*"); // 2允許任何頭
    corsConfiguration.addAllowedMethod("*"); // 3允許任何方法(post、get等)
    corsConfiguration.setAllowCredentials(true);
    return corsConfiguration;
  } 

  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", buildConfig()); // 4
    return new CorsFilter(source);
  }
}

時間過去一小時了,又過去一小時了,我用Swagger是一點問題都沒有,可還是請求不了,我覺得是我的思路錯了,於是我矛頭轉向SpringSecurity

我把攔截請求關了,可以訪問了,打開又不可以訪問了,真是頭皮發麻。

下面這句就是在SpringSecurity配置文件裏面攔截請求的了

 //攔截其他所有請求
.anyRequest().authenticated()

所以事實證明,SpringSecurity有問題。

於是我查詢資料知道

加一句代碼就ok了

.and()
.cors()
//攔截其他所有請求
.anyRequest().authenticated()
.and()
.cors()
.and().csrf().disable();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章