You are here

public function ApiTest::testNotAllowed in Lightning API 8

Same name and namespace in other branches
  1. 8.2 modules/api_test/tests/src/Functional/ApiTest.php \Drupal\Tests\api_test\Functional\ApiTest::testNotAllowed()

Tests that authenticated and anonymous requests cannot get unauthorized data.

File

modules/api_test/tests/src/Functional/ApiTest.php, line 88

Class

ApiTest
Tests that OAuth and json:api are working together to authenticate, authorize and allow/forbid interaction with entities as designed.

Namespace

Drupal\Tests\api_test\Functional

Code

public function testNotAllowed() {

  // Cannot get unauthorized data (not in role/scope) even when authenticated.
  $response = $this
    ->request('/jsonapi/user_role/user_role', 'get', $this->token);
  $body = $this
    ->decodeResponse($response);
  $this
    ->assertArrayHasKey('errors', $body['meta']);
  foreach ($body['meta']['errors'] as $error) {

    // This user/client should not have access to any of the roles' data. JSON
    // API will still return a 200, but with a list of 403 errors in the body.
    $this
      ->assertEquals(403, $error['status']);
  }

  // Cannot get unauthorized data anonymously.
  $client = $this->container
    ->get('http_client');
  $url = $this
    ->buildUrl('/jsonapi/node/page/api_test-unpublished-page-content');

  // Unlike the roles test which requests a list, JSON API sends a 403 status
  // code when requesting a specific unauthorized resource instead of list.
  $this
    ->setExpectedException(ClientException::class, 'Client error: `GET ' . $url . '` resulted in a `403 Forbidden`');
  $client
    ->get($url);
}