View source
<?php
namespace Drupal\FunctionalTests\HttpKernel;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
class CorsIntegrationTest extends BrowserTestBase {
public static $modules = [
'system',
'test_page_test',
'page_cache',
];
protected $defaultTheme = 'stark';
public function testCrossSiteRequest() {
$cors_config = $this->container
->getParameter('cors.config');
$this
->assertSame(FALSE, $cors_config['enabled']);
$this
->assertSame([], $cors_config['allowedHeaders']);
$this
->assertSame([], $cors_config['allowedMethods']);
$this
->assertSame([
'*',
], $cors_config['allowedOrigins']);
$this
->assertSame(FALSE, $cors_config['exposedHeaders']);
$this
->assertSame(FALSE, $cors_config['maxAge']);
$this
->assertSame(FALSE, $cors_config['supportsCredentials']);
$cors_config['enabled'] = TRUE;
$this
->setContainerParameter('cors.config', $cors_config);
$this
->rebuildContainer();
$this
->drupalGet('/test-page', [], [
'Origin' => 'http://example.com',
]);
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->responseHeaderEquals('X-Drupal-Cache', 'MISS');
$this
->assertSession()
->responseHeaderEquals('Access-Control-Allow-Origin', 'http://example.com');
$this
->drupalGet('/test-page', [], [
'Origin' => 'http://example.com',
]);
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->responseHeaderEquals('X-Drupal-Cache', 'HIT');
$this
->assertSession()
->responseHeaderEquals('Access-Control-Allow-Origin', 'http://example.com');
$this
->drupalGet('/test-page', [], [
'Origin' => 'http://example.org',
]);
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->responseHeaderEquals('X-Drupal-Cache', 'HIT');
$this
->assertSession()
->responseHeaderEquals('Access-Control-Allow-Origin', 'http://example.org');
$cors_config['allowedOrigins'] = [
'http://example.com',
];
$this
->setContainerParameter('cors.config', $cors_config);
$this
->rebuildContainer();
$this
->drupalGet('/test-page', [], [
'Origin' => 'http://non-valid.com',
]);
$this
->assertSession()
->statusCodeEquals(403);
$this
->assertSession()
->pageTextContains('Not allowed.');
$this
->drupalGet('/test-page', [], [
'Origin' => 'http://example.com',
]);
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->responseHeaderEquals('Access-Control-Allow-Origin', 'http://example.com');
$origin = \Drupal::request()
->getSchemeAndHttpHost();
$httpClient = $this
->getSession()
->getDriver()
->getClient()
->getClient();
$url = Url::fromUri('base:/test-page');
$response = $httpClient
->request('POST', $url
->setAbsolute()
->toString(), [
'headers' => [
'Origin' => $origin,
],
]);
$this
->assertEquals(200, $response
->getStatusCode());
}
}