3 namespace Drupal\Tests\system\Functional;
6 use Drupal\Tests\BrowserTestBase;
7 use GuzzleHttp\Cookie\CookieJar;
10 * Tests protecting routes by requiring CSRF token in the request header.
14 class CsrfRequestHeaderTest extends BrowserTestBase {
21 public static $modules = ['system', 'csrf_test'];
24 * Tests access to routes protected by CSRF request header requirements.
26 * This checks one route that uses _csrf_request_header_token and one that
27 * uses the deprecated _access_rest_csrf.
29 public function testRouteAccess() {
30 $client = \Drupal::httpClient();
31 $csrf_token_paths = ['deprecated/session/token', 'session/token'];
32 // Test using the both the current path and a test path that returns
33 // a token using the deprecated 'rest' value.
34 // Checking /deprecated/session/token can be removed in 8.3.
35 // @see \Drupal\Core\Access\CsrfRequestHeaderAccessCheck::access()
36 foreach ($csrf_token_paths as $csrf_token_path) {
37 // Check both test routes.
38 $route_names = ['csrf_test.protected', 'csrf_test.deprecated.protected'];
39 foreach ($route_names as $route_name) {
40 $user = $this->drupalCreateUser();
41 $this->drupalLogin($user);
43 $csrf_token = $this->drupalGet($csrf_token_path);
44 $url = Url::fromRoute($route_name)
47 $domain = parse_url($url, PHP_URL_HOST);
49 $session_id = $this->getSession()->getCookie($this->getSessionName());
50 /** @var \GuzzleHttp\Cookie\CookieJar $cookies */
51 $cookies = CookieJar::fromArray([$this->getSessionName() => $session_id], $domain);
53 'headers' => ['Accept' => 'text/plain'],
54 'http_errors' => FALSE,
57 // Test that access is allowed for anonymous user with no token in header.
58 $result = $client->post($url, $post_options);
59 $this->assertEquals(200, $result->getStatusCode());
61 // Add cookies to POST options so that all other requests are for the
62 // authenticated user.
63 $post_options['cookies'] = $cookies;
65 // Test that access is denied with no token in header.
66 $result = $client->post($url, $post_options);
67 $this->assertEquals(403, $result->getStatusCode());
69 // Test that access is allowed with correct token in header.
70 $post_options['headers']['X-CSRF-Token'] = $csrf_token;
71 $result = $client->post($url, $post_options);
72 $this->assertEquals(200, $result->getStatusCode());
74 // Test that access is denied with incorrect token in header.
75 $post_options['headers']['X-CSRF-Token'] = 'this-is-not-the-token-you-are-looking-for';
76 $result = $client->post($url, $post_options);
77 $this->assertEquals(403, $result->getStatusCode());