3 namespace Drupal\FunctionalTests\HttpKernel;
5 use Drupal\Tests\BrowserTestBase;
8 * Tests CORS provided by Drupal.
10 * @see sites/default/default.services.yml
11 * @see \Asm89\Stack\Cors
12 * @see \Asm89\Stack\CorsService
16 class CorsIntegrationTest extends BrowserTestBase {
21 public static $modules = ['system', 'test_page_test', 'page_cache'];
23 public function testCrossSiteRequest() {
24 // Test default parameters.
25 $cors_config = $this->container->getParameter('cors.config');
26 $this->assertSame(FALSE, $cors_config['enabled']);
27 $this->assertSame([], $cors_config['allowedHeaders']);
28 $this->assertSame([], $cors_config['allowedMethods']);
29 $this->assertSame(['*'], $cors_config['allowedOrigins']);
31 $this->assertSame(FALSE, $cors_config['exposedHeaders']);
32 $this->assertSame(FALSE, $cors_config['maxAge']);
33 $this->assertSame(FALSE, $cors_config['supportsCredentials']);
35 // Enable CORS with the default options.
36 $cors_config['enabled'] = TRUE;
38 $this->setContainerParameter('cors.config', $cors_config);
39 $this->rebuildContainer();
41 // Fire off a request.
42 $this->drupalGet('/test-page', [], ['Origin' => 'http://example.com']);
43 $this->assertSession()->statusCodeEquals(200);
44 $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'MISS');
45 $this->assertSession()->responseHeaderEquals('Access-Control-Allow-Origin', 'http://example.com');
47 // Fire the same exact request. This time it should be cached.
48 $this->drupalGet('/test-page', [], ['Origin' => 'http://example.com']);
49 $this->assertSession()->statusCodeEquals(200);
50 $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'HIT');
51 $this->assertSession()->responseHeaderEquals('Access-Control-Allow-Origin', 'http://example.com');
53 // Fire a request for a different origin. Verify the CORS header.
54 $this->drupalGet('/test-page', [], ['Origin' => 'http://example.org']);
55 $this->assertSession()->statusCodeEquals(200);
56 $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'HIT');
57 $this->assertSession()->responseHeaderEquals('Access-Control-Allow-Origin', 'http://example.org');
59 // Configure the CORS stack to allow a specific set of origins.
60 $cors_config['allowedOrigins'] = ['http://example.com'];
62 $this->setContainerParameter('cors.config', $cors_config);
63 $this->rebuildContainer();
65 // Fire a request from an origin that isn't allowed.
66 /** @var \Symfony\Component\HttpFoundation\Response $response */
67 $this->drupalGet('/test-page', [], ['Origin' => 'http://non-valid.com']);
68 $this->assertSession()->statusCodeEquals(403);
69 $this->assertSession()->pageTextContains('Not allowed.');
71 // Specify a valid origin.
72 $this->drupalGet('/test-page', [], ['Origin' => 'http://example.com']);
73 $this->assertSession()->statusCodeEquals(200);
74 $this->assertSession()->responseHeaderEquals('Access-Control-Allow-Origin', 'http://example.com');