You are here

public function AuthTest::testRead in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/rest/src/Tests/AuthTest.php \Drupal\rest\Tests\AuthTest::testRead()

Tests reading from an authenticated resource.

File

core/modules/rest/src/Tests/AuthTest.php, line 29
Contains \Drupal\rest\Tests\AuthTest.

Class

AuthTest
Tests authentication provider restrictions.

Namespace

Drupal\rest\Tests

Code

public function testRead() {
  $entity_type = 'entity_test';

  // Enable a test resource through GET method and basic HTTP authentication.
  $this
    ->enableService('entity:' . $entity_type, 'GET', NULL, array(
    'basic_auth',
  ));

  // Create an entity programmatically.
  $entity = $this
    ->entityCreate($entity_type);
  $entity
    ->save();

  // Try to read the resource as an anonymous user, which should not work.
  $this
    ->httpRequest($entity
    ->urlInfo()
    ->setRouteParameter('_format', $this->defaultFormat), 'GET');
  $this
    ->assertResponse('401', 'HTTP response code is 401 when the request is not authenticated and the user is anonymous.');
  $this
    ->assertRaw(json_encode([
    'message' => 'A fatal error occurred: No authentication credentials provided.',
  ]));

  // Ensure that cURL settings/headers aren't carried over to next request.
  unset($this->curlHandle);

  // Create a user account that has the required permissions to read
  // resources via the REST API, but the request is authenticated
  // with session cookies.
  $permissions = $this
    ->entityPermissions($entity_type, 'view');
  $permissions[] = 'restful get entity:' . $entity_type;
  $account = $this
    ->drupalCreateUser($permissions);
  $this
    ->drupalLogin($account);

  // Try to read the resource with session cookie authentication, which is
  // not enabled and should not work.
  $this
    ->httpRequest($entity
    ->urlInfo()
    ->setRouteParameter('_format', $this->defaultFormat), 'GET');
  $this
    ->assertResponse('403', 'HTTP response code is 403 when the request was authenticated by the wrong authentication provider.');

  // Ensure that cURL settings/headers aren't carried over to next request.
  unset($this->curlHandle);

  // Now read it with the Basic authentication which is enabled and should
  // work.
  $this
    ->basicAuthGet($entity
    ->urlInfo()
    ->setRouteParameter('_format', $this->defaultFormat), $account
    ->getUsername(), $account->pass_raw);
  $this
    ->assertResponse('200', 'HTTP response code is 200 for successfully authenticated requests.');
  $this
    ->curlClose();
}