You are here

function OAuthTest::testRequestAuthentication in OAuth 1.0 8

Same name and namespace in other branches
  1. 8.2 src/Tests/OAuthTest.php \Drupal\oauth\Tests\OAuthTest::testRequestAuthentication()

Tests OAuth authentication in requests.

File

src/Tests/OAuthTest.php, line 55
Contains \Drupal\oauth\Tests\OAuthTest.

Class

OAuthTest
Tests oauth functionality.

Namespace

Drupal\oauth\Tests

Code

function testRequestAuthentication() {
  $entity_type = 'entity_test';
  $resource = 'entity:' . $entity_type;
  $method = 'GET';
  $format = 'json';

  // Allow GET requests through OAuth on entity_test.
  $config = \Drupal::configFactory()
    ->getEditable('rest.settings');
  $settings = array();
  $settings[$resource][$method]['supported_formats'][] = $format;
  $settings[$resource][$method]['supported_auth'][] = 'oauth';
  $config
    ->set('resources', $settings);
  $config
    ->save();
  $this->container
    ->get('router.builder')
    ->rebuild();

  // Create an entity programmatically.
  $entity_values = array(
    'name' => 'Some name',
    'user_id' => 1,
    'field_test_text' => array(
      0 => array(
        'value' => 'Some value',
        'format' => 'plain_text',
      ),
    ),
  );
  $entity = entity_create($entity_type, $entity_values);
  $entity
    ->save();

  // Create a user account that has the required permissions to read
  // resources via the REST API.
  $permissions = array(
    'view test entity',
    'restful get entity:' . $entity_type,
    'access own consumers',
  );
  $account = $this
    ->drupalCreateUser($permissions);
  $this
    ->drupalLogin($account);

  // Generate a set of consumer keys.
  $this
    ->drupalPostForm('oauth/consumer/add', array(), 'Add');
  $consumer = db_query('select * from {oauth_consumer} where uid = :uid', array(
    ':uid' => $account
      ->id(),
  ))
    ->fetchObject();

  // Now send an authenticated request to read the entity through REST.
  $url = $entity
    ->urlInfo()
    ->setRouteParameter('_format', $format);
  $endpoint = $url
    ->setAbsolute()
    ->toString();
  $oauth = new \OAuth($consumer->consumer_key, $consumer->consumer_secret);
  $oauth_header = $oauth
    ->getRequestHeader('GET', $endpoint);
  $out = $this
    ->curlExec(array(
    CURLOPT_HTTPGET => TRUE,
    CURLOPT_NOBODY => FALSE,
    CURLOPT_URL => $endpoint,
    CURLOPT_HTTPHEADER => array(
      'Authorization: ' . $oauth_header,
    ),
  ));
  $this
    ->verbose('GET request to: ' . $endpoint . '<hr />' . $out);
  $this
    ->assertResponse('200', 'HTTP response code is 200 for successfully authenticated request.');
  $this
    ->curlClose();
}