spring-boot-plus CORS跨域處理

CORS跨域處理

CORS:Cross-Origin Resource Sharing
  • CORS是一種允許當前域(domain)的資源(比如html/js/web service)被其他域(domain)的腳本請求訪問的機制,通常由於同域安全策略(the same-origin security policy)瀏覽器會禁止這種跨域請求。

處理方法

  • 後臺設置允許的請求源/請求頭等信息

後臺配置

CorsFilter Bean配置

使用 Spring 提供的 CorsFilter 過濾器實現跨域配置
  • io.geekidea.springbootplus.core.config.SpringBootPlusCorsConfig
/**
 * CORS跨域設置
 *
 * @return
 */
@Bean
public FilterRegistrationBean corsFilter(SpringBootPlusCorsProperties corsProperties) {
    log.debug("corsProperties:{}", corsProperties);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    // 跨域配置
    corsConfiguration.setAllowedOrigins(corsProperties.getAllowedOrigins());
    corsConfiguration.setAllowedHeaders(corsProperties.getAllowedHeaders());
    corsConfiguration.setAllowedMethods(corsProperties.getAllowedMethods());
    corsConfiguration.setAllowCredentials(corsProperties.isAllowCredentials());
    corsConfiguration.setExposedHeaders(corsProperties.getExposedHeaders());
    corsConfiguration.setMaxAge(corsConfiguration.getMaxAge());

    source.registerCorsConfiguration(corsProperties.getPath(), corsConfiguration);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    bean.setEnabled(corsProperties.isEnable());
    return bean;
}

配置文件

配置文件類:io.geekidea.springbootplus.core.properties.SpringBootPlusCorsProperties
  • application.yml
spring-boot-plus:
  ############################ CORS start ############################
  # CORS跨域配置,默認允許跨域
  cors:
    # 是否啓用跨域,默認啓用
    enable: true
    # CORS過濾的路徑,默認:/**
    path: /**
    # 允許訪問的源
    allowed-origins: '*'
    # 允許訪問的請求頭
    allowed-headers: x-requested-with,content-type,token
    # 是否允許發送cookie
    allow-credentials: true
    # 允許訪問的請求方式
    allowed-methods: OPTION,GET,POST
    # 允許響應的頭
    exposed-headers: token
    # 該響應的有效時間默認爲30分鐘,在有效時間內,瀏覽器無須爲同一請求再次發起預檢請求
    max-age: 1800
  ############################ CORS end ##############################

參考

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