drupalCreateUser(); $this->drupalLogin($user); $csrf_token = $this->drupalGet($csrf_token_path); $url = Url::fromRoute($route_name) ->setAbsolute(TRUE) ->toString(); $domain = parse_url($url, PHP_URL_HOST); $session_id = $this->getSession()->getCookie($this->getSessionName()); /** @var \GuzzleHttp\Cookie\CookieJar $cookies */ $cookies = CookieJar::fromArray([$this->getSessionName() => $session_id], $domain); $post_options = [ 'headers' => ['Accept' => 'text/plain'], 'http_errors' => FALSE, ]; // Test that access is allowed for anonymous user with no token in header. $result = $client->post($url, $post_options); $this->assertEquals(200, $result->getStatusCode()); // Add cookies to POST options so that all other requests are for the // authenticated user. $post_options['cookies'] = $cookies; // Test that access is denied with no token in header. $result = $client->post($url, $post_options); $this->assertEquals(403, $result->getStatusCode()); // Test that access is allowed with correct token in header. $post_options['headers']['X-CSRF-Token'] = $csrf_token; $result = $client->post($url, $post_options); $this->assertEquals(200, $result->getStatusCode()); // Test that access is denied with incorrect token in header. $post_options['headers']['X-CSRF-Token'] = 'this-is-not-the-token-you-are-looking-for'; $result = $client->post($url, $post_options); $this->assertEquals(403, $result->getStatusCode()); } } } }