解决跨域问题之预检请求
预检请求(Preflight Request)是跨域资源共享(CORS)中用于安全检查的一种机制。
它是由浏览器自动发起的一个OPTIONS请求,目的是在实际跨域请求之前,询问服务器是否允许这次跨域操作。
当浏览器发起一个跨域请求(即跨域资源请求)时,如果请求方法不是简单请求(例如 GET 或 POST),或者请求头包含非简单头部(例如自定义请求头),浏览器会先发送一个预检请求。
@Configuration
public class CorsConfig { private static final String MAX_AGE = "18000L" ; @Bean public WebFilter corsFilter ( ) { return ( ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) -> { ServerHttpRequest request = serverWebExchange. getRequest ( ) ; if ( ! CorsUtils . isCorsRequest ( request) ) { return webFilterChain. filter ( serverWebExchange) ; } HttpHeaders httpHeaders = request. getHeaders ( ) ; ServerHttpResponse response = serverWebExchange. getResponse ( ) ; HttpMethod requestMethod = httpHeaders. getAccessControlRequestMethod ( ) ; HttpHeaders responseHeaders = response. getHeaders ( ) ; responseHeaders. add ( HttpHeaders . ACCESS_CONTROL_ALLOW_ORIGIN , httpHeaders. getOrigin ( ) ) ;
responseHeaders. addAll ( HttpHeaders . ACCESS_CONTROL_ALLOW_HEADERS , httpHeaders. getAccessControlRequestHeaders ( ) ) ; if ( requestMethod != null ) { responseHeaders. add ( HttpHeaders . ACCESS_CONTROL_ALLOW_METHODS , requestMethod. name ( ) ) ; } responseHeaders. add ( HttpHeaders . ACCESS_CONTROL_ALLOW_CREDENTIALS , "true" ) ; responseHeaders. add ( HttpHeaders . ACCESS_CONTROL_EXPOSE_HEADERS , "*" ) ; responseHeaders. add ( HttpHeaders . ACCESS_CONTROL_MAX_AGE , MAX_AGE ) ; if ( request. getMethod ( ) == HttpMethod . OPTIONS ) { response. setStatusCode ( HttpStatus . OK ) ; return Mono . empty ( ) ; } return webFilterChain. filter ( serverWebExchange) ; } ; }
}