You are here

public function OAuth2ServerTest::testCryptoTokens in OAuth2 Server 8

Same name and namespace in other branches
  1. 2.0.x tests/src/Functional/OAuth2ServerTest.php \Drupal\Tests\oauth2_server\Functional\OAuth2ServerTest::testCryptoTokens()

Tests crypto tokens.

File

tests/src/Functional/OAuth2ServerTest.php, line 527

Class

OAuth2ServerTest
The OAuth2 Server admin test case.

Namespace

Drupal\Tests\oauth2_server\Functional

Code

public function testCryptoTokens() {

  // Enable crypto tokens.
  $server = $this->container
    ->get('entity_type.manager')
    ->getStorage('oauth2_server')
    ->load('test_server');
  $server->settings['use_crypto_tokens'] = TRUE;
  $server
    ->save();
  $response = $this
    ->passwordGrantRequest();
  $this
    ->assertEqual($response
    ->getStatusCode(), 200, 'The token request completed successfully');
  $payload = json_decode($response
    ->getBody());

  // The refresh token is contained inside the crypto token.
  $this
    ->assertTokenResponse($payload, FALSE);
  $verified = FALSE;
  if (substr_count($payload->access_token, '.') == 2) {

    // Verify the JTW Access token following the instructions from
    // http://bshaffer.github.io/oauth2-server-php-docs/overview/jwt-access-tokens
    // phpcs:ignore Drupal.Arrays.Array.LongLineDeclaration
    [
      $header,
      $token_payload,
      $signature,
    ] = explode('.', $payload->access_token);

    // The signature is "url safe base64 encoded".
    $signature = base64_decode(strtr($signature, '-_,', '+/'));
    $payload_to_verify = utf8_decode($header . '.' . $token_payload);
    $verified = (bool) openssl_verify($payload_to_verify, $signature, $this->publicKey, 'sha256');
  }
  $this
    ->assertTrue($verified, 'The JWT Access Token is valid.');
}