3 namespace Drupal\Tests\system\Functional;
6 use Drupal\Tests\BrowserTestBase;
9 * Tests protecting routes by requiring CSRF token in the request header.
13 class CsrfRequestHeaderTest extends BrowserTestBase {
20 public static $modules = ['system', 'csrf_test'];
23 * Tests access to routes protected by CSRF request header requirements.
25 * This checks one route that uses _csrf_request_header_token and one that
26 * uses the deprecated _access_rest_csrf.
28 public function testRouteAccess() {
29 $client = $this->getHttpClient();
30 $csrf_token_paths = ['deprecated/session/token', 'session/token'];
31 // Test using the both the current path and a test path that returns
32 // a token using the deprecated 'rest' value.
33 // Checking /deprecated/session/token can be removed in 8.3.
34 // @see \Drupal\Core\Access\CsrfRequestHeaderAccessCheck::access()
35 foreach ($csrf_token_paths as $csrf_token_path) {
36 // Check both test routes.
37 $route_names = ['csrf_test.protected', 'csrf_test.deprecated.protected'];
38 foreach ($route_names as $route_name) {
39 $user = $this->drupalCreateUser();
40 $this->drupalLogin($user);
42 $csrf_token = $this->drupalGet($csrf_token_path);
43 $url = Url::fromRoute($route_name)
47 'headers' => ['Accept' => 'text/plain'],
48 'http_errors' => FALSE,
51 // Test that access is allowed for anonymous user with no token in header.
52 $result = $client->post($url, $post_options);
53 $this->assertEquals(200, $result->getStatusCode());
55 // Add cookies to POST options so that all other requests are for the
56 // authenticated user.
57 $post_options['cookies'] = $this->getSessionCookies();
59 // Test that access is denied with no token in header.
60 $result = $client->post($url, $post_options);
61 $this->assertEquals(403, $result->getStatusCode());
63 // Test that access is allowed with correct token in header.
64 $post_options['headers']['X-CSRF-Token'] = $csrf_token;
65 $result = $client->post($url, $post_options);
66 $this->assertEquals(200, $result->getStatusCode());
68 // Test that access is denied with incorrect token in header.
69 $post_options['headers']['X-CSRF-Token'] = 'this-is-not-the-token-you-are-looking-for';
70 $result = $client->post($url, $post_options);
71 $this->assertEquals(403, $result->getStatusCode());