java web cors-filter 跨域开源库springboot 配置
本次配置基于springboot 配置:
1. 加入maven 依赖
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.6</version>
</dependency>
2. springboot 注册 filter
import com.thetransactioncompany.cors.CORSFilter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "cors") public class CorsConfiguration { private String legalClients ; public void setLegalClients(String legalClients) { this.legalClients = legalClients; } @Bean public FilterRegistrationBean someFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.addInitParameter("cors.allowSubdomains","true"); // 是否开启二级域名跨域 registration.addInitParameter("cors.allowOrigin",legalClients);// 放行的域名list 以"," 号分割 registration.addUrlPatterns("/*"); CORSFilter corsFilter= new CORSFilter(); registration.setName("CORSFilter"); registration.setFilter(corsFilter); return registration; } }
3. springboot application.yml 配置
cors: legal-clients: https://h5.shanhulicai.cn,https://p.blackfish.cn,https://depo.xwbank.com,http://omniaccount.com
完成配置。
---------------------------------------------------------------------------------------
简单解析跨域配置原理:
1. 浏览器会判断跨域访问发送options预请,附带header origin = http://omniaccount.com ;
2. 服务器收到 option会检测放心原则如下:
·1)判断是否开启了 allowAnyOrigin = true
2) 判断是否在允许放行的 list 列表集合内(legal-clients)
3)判断是否开启了允许二级域名跨域配置且请求域名在允许的列表内
服务器如果判断为false ,会发送 403 CORS origin denied, 为true 会发送 200 ,跨域放行
3.浏览器判断如果200,返回成功,继续后续的实际请求