/** * Get a single value for the "Access-Control-Allow-Origin" header * * According to the spec, it is not valid to set multiple origins separated by commas. Only accepted * value are wildcard ("*"), an exact domain or a null string. * * @link http://www.w3.org/TR/cors/#access-control-allow-origin-response-header * @param HttpRequest $request * @return string */ protected function getAllowedOriginValue(HttpRequest $request) { $allowedOrigins = $this->options->getAllowedOrigins(); if (in_array('*', $allowedOrigins)) { return '*'; } $origin = $request->getHeader('Origin')->getFieldValue(); foreach ($allowedOrigins as $allowedOrigin) { if (fnmatch($allowedOrigin, $origin)) { return $origin; } } return 'null'; }
public function testCanModifyOptions() { $options = new CorsOptions(); $options->setAllowedOrigins(array('http://example1.com', 'http://example2.com')); $this->assertEquals(array('http://example1.com', 'http://example2.com'), $options->getAllowedOrigins()); $options->setAllowedMethods(array('POST', 'GET')); $this->assertEquals(array('POST', 'GET'), $options->getAllowedMethods()); $options->setAllowedHeaders(array('Content-Type')); $this->assertEquals(array('Content-Type'), $options->getAllowedHeaders()); $options->setMaxAge(30); $this->assertEquals(30, $options->getMaxAge()); $options->setExposedHeaders(array('Location', 'X-Custom-Header')); $this->assertEquals(array('Location', 'X-Custom-Header'), $options->getExposedHeaders()); $options->setAllowedCredentials(true); $this->assertTrue($options->getAllowedCredentials()); }
/** * Ensure that the Vary header is set. * * * @link http://www.w3.org/TR/cors/#resource-implementation * @param HttpResponse $response * @return \Zend\Http\Headers */ public function ensureVaryHeader(HttpResponse $response) { $headers = $response->getHeaders(); // If the origin is not "*", we should add the "Origin" value to the "Vary" header // See more: http://www.w3.org/TR/cors/#resource-implementation $allowedOrigins = $this->options->getAllowedOrigins(); if (in_array('*', $allowedOrigins)) { return $headers; } if ($headers->has('Vary')) { $varyHeader = $headers->get('Vary'); $varyValue = $varyHeader->getFieldValue() . ', Origin'; $headers->removeHeader($varyHeader); $headers->addHeaderLine('Vary', $varyValue); } else { $headers->addHeaderLine('Vary', 'Origin'); } return $headers; }