Automattic\WooCommerce\StoreApi
Authentication::send_cors_headers
Add CORS headers to a response object.
These checks prevent access to the Store API from non-allowed origins. By default, the WordPress REST API allows access from any origin. Because some Store API routes return PII, we need to add our own CORS headers.
Allowed origins can be changed using the WordPress allowed_http_origins allowed_http_origin if access needs to be granted to other domains.
Users of valid Cart Tokens are also allowed access from any origin.
Method of the class: Authentication{}
No Hooks.
Returns
true|false.
Usage
$Authentication = new Authentication(); $Authentication->send_cors_headers( $served, $result, $request, $server );
- $served(true|false) (required)
- Whether the request has already been served.
- $result(WP_REST_Response) (required)
- The response object.
- $request(WP_REST_Request) (required)
- The request object.
- $server(WP_REST_Server) (required)
- The REST server instance.
Authentication::send_cors_headers() Authentication::send cors headers code WC 10.7.0
public function send_cors_headers( $served, $result, $request, $server ) {
$origin = get_http_origin();
if ( 'null' !== $origin ) {
$origin = esc_url_raw( $origin );
}
// Send standard CORS headers.
$server->send_header( 'Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE' );
$server->send_header( 'Access-Control-Allow-Credentials', 'true' );
$server->send_header( 'Vary', 'Origin', false );
// Allow preflight requests, certain http origins, and any origin if a cart token is present. Preflight requests
// are allowed because we'll be unable to validate cart token headers at that point.
if ( $this->is_preflight() || CartTokenUtils::validate_cart_token( $this->get_cart_token( $request ) ) || is_allowed_http_origin( $origin ) ) {
$server->send_header( 'Access-Control-Allow-Origin', $origin );
}
// Exit early during preflight requests. This is so someone cannot access API data by sending an OPTIONS request
// with preflight headers and a _GET property to override the method.
if ( $this->is_preflight() ) {
exit;
}
return $served;
}