You are here

class OAuth2ServerTest in OAuth2 Server 2.0.x

Same name and namespace in other branches
  1. 8 tests/src/Functional/OAuth2ServerTest.php \Drupal\Tests\oauth2_server\Functional\OAuth2ServerTest

The OAuth2 Server admin test case.

@group oauth2_server

Hierarchy

Expanded class hierarchy of OAuth2ServerTest

File

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

Namespace

Drupal\Tests\oauth2_server\Functional
View source
class OAuth2ServerTest extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stable';

  /**
   * {@inheritdoc}
   */
  public static $modules = [
    'oauth2_server',
    'oauth2_server_test',
  ];

  /**
   * The client key of the test client.
   *
   * @var string
   */
  protected $clientId = 'test_client';

  /**
   * The client secret of the test client.
   *
   * @var string
   */
  protected $clientSecret = 'test_secret';

  /**
   * The redirect uri used on multiple locations.
   *
   * @var string
   */
  protected $redirectUri;

  /**
   * The public key X.509 certificate used for all tests with encryption.
   *
   * @var string
   */
  protected $publicKey = '-----BEGIN CERTIFICATE-----
MIIDMDCCApmgAwIBAgIBADANBgkqhkiG9w0BAQQFADB0MS0wKwYDVQQDEyRodHRw
czovL21hcmtldHBsYWNlLmludGVybmFsLmMtZy5pby8xCzAJBgNVBAYTAkFVMRMw
EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
eSBMdGQwHhcNMTQwMTIxMTYyMzAyWhcNMTQwMTIzMTYyMzAyWjB0MS0wKwYDVQQD
EyRodHRwczovL21hcmtldHBsYWNlLmludGVybmFsLmMtZy5pby8xCzAJBgNVBAYT
AkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRn
aXRzIFB0eSBMdGQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANVMpjmyWlaD
6N1x1O4cf5PB6fXjq4dx1zKh/znG/zMJhkaT0TNJDD+3zfpJYFFxZGrbde+dYinL
jDK+ROvq7+h+93r0eWrld+R/kNWgILJtWwXQACPDd0pVtdOiSSd90QSEfRZyyYCl
n8RvVIPdPbGiPtDQGDwV5Dc5WcupdJNBAgMBAAGjgdEwgc4wHQYDVR0OBBYEFO4C
ZtCI7/REm9UO+PFpbAAsHHOUMIGeBgNVHSMEgZYwgZOAFO4CZtCI7/REm9UO+PFp
bAAsHHOUoXikdjB0MS0wKwYDVQQDEyRodHRwczovL21hcmtldHBsYWNlLmludGVy
bmFsLmMtZy5pby8xCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEw
HwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGSCAQAwDAYDVR0TBAUwAwEB
/zANBgkqhkiG9w0BAQQFAAOBgQCSCeFzNdUeFh0yNVatOdQpm2du1v7A4NXpdWL5
tXJQpv3Vgohc9f2GrVr1np270aJ3rzmSrWugZRHx0A3zhuYTNsapacvIOqmffPHd
0IZVnRgXnHPqwnWqMWuNtb8DglEEjKarjnOos/RbGvbirWsAJObxnt9kfI5wUOoA
0mYehA==
-----END CERTIFICATE-----';

  /**
   * The private key used for all tests with encryption.
   *
   * @var string
   */
  protected $privateKey = '-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDVTKY5slpWg+jdcdTuHH+Twen146uHcdcyof85xv8zCYZGk9Ez
SQw/t836SWBRcWRq23XvnWIpy4wyvkTr6u/ofvd69Hlq5Xfkf5DVoCCybVsF0AAj
w3dKVbXTokknfdEEhH0WcsmApZ/Eb1SD3T2xoj7Q0Bg8FeQ3OVnLqXSTQQIDAQAB
AoGAa/aEHKgd+bSC5bN8Z5mdKZj5ZzB53fDNUB+XJBOJkLe9c3PWa/MJdCcA5zLE
wfR3M28p3sL2sNkKeZS9JfyguU0QQzMhrnJZMSwPzrcUEVcRI/3vCvgnWr/4UFBW
JQpdWGvmk9MNg83y/ddnIBHEQRI9POz/dt/4L58Vq5YUy8ECQQDuWHV2nMmvuAiW
/s+D+S8arhfUyupNEVhNvpqMxK/25s4rUHGadIWm2TPStWEyxQGE4Om4bcw8KOLw
iAeKQ/qFAkEA5RlDJHz0CEgW4+bM+rOIi+tLB2C+TLzKH0eDGpeImAdsk4Z53Lxm
22iZm3DtkEqrrl+bYiaQVFovtbd5wmS4jQJBALFlcXfo1kxNA0evO7CUZLTM4rvk
k2LtB/ZFaS5grj9sJgMjCorVMyyt+N5ZVZC+BJVr+Ujln98e51nzRPlqAykCQQC/
9rT94/2O2ujjOcdT4g9uPk/19KhAIIi0QPWn2IVJ7h6aVrnRrcP54OGlD7DfkNHe
IJpQWcPiClejygMqUb8ZAkEA6SFArj46gwFaERr+D8wMizfZdxhzEuMMG3angAuV
1VPFI7qyv4rtDVATTk8RXeXUcP7l3JaQbqh+Jf0d1eSUpg==
-----END RSA PRIVATE KEY-----';

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->redirectUri = $this
      ->buildUrl('/user', [
      'absolute' => TRUE,
    ]);

    // Set the keys so that the module can see them.
    $keys = [
      'public_key' => $this->publicKey,
      'private_key' => $this->privateKey,
    ];
    \Drupal::state()
      ->set('oauth2_server.keys', $keys);
    \Drupal::state()
      ->set('oauth2_server.last_generated', \Drupal::time()
      ->getRequestTime());

    /** @var \Drupal\oauth2_server\ServerInterface $server */
    $server = $this->container
      ->get('entity_type.manager')
      ->getStorage('oauth2_server')
      ->create([
      'server_id' => 'test_server',
      'name' => 'Test Server',
      'settings' => [
        'default_scope' => 'test_server_basic',
        'enforce_state' => TRUE,
        'allow_implicit' => TRUE,
        'use_openid_connect' => TRUE,
        'use_crypto_tokens' => FALSE,
        'store_encrypted_token_string' => FALSE,
        'grant_types' => [
          'authorization_code' => 'authorization_code',
          'client_credentials' => 'client_credentials',
          'urn:ietf:params:oauth:grant-type:jwt-bearer' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
          'refresh_token' => 'refresh_token',
          'password' => 'password',
        ],
        'always_issue_new_refresh_token' => TRUE,
        'advanced_settings' => [
          'require_exact_redirect_uri' => TRUE,
          'access_lifetime' => 3600,
          'id_lifetime' => 3600,
          'refresh_token_lifetime' => 1209600,
        ],
      ],
    ]);
    $server
      ->save();

    /** @var \Drupal\oauth2_server\ClientInterface $client */
    $client = $this->container
      ->get('entity_type.manager')
      ->getStorage('oauth2_server_client')
      ->create([
      'client_id' => $this->clientId,
      'server_id' => $server
        ->id(),
      'name' => 'Test client',
      'unhashed_client_secret' => $this->clientSecret,
      'public_key' => $this->publicKey,
      'redirect_uri' => 'https://google.com' . "\n" . $this->redirectUri,
      'automatic_authorization' => TRUE,
    ]);
    $client
      ->save();
    $scopes = [
      'basic' => 'Basic',
      'admin' => 'Admin',
      'forbidden' => 'Forbidden',
      'phone' => 'phone',
    ];
    foreach ($scopes as $scope_name => $scope_label) {
      $scope = $this->container
        ->get('entity_type.manager')
        ->getStorage('oauth2_server_scope')
        ->create([
        'scope_id' => $scope_name,
        'server_id' => $server
          ->id(),
        'description' => $scope_label,
      ]);
      $scope
        ->save();
    }
  }

  /**
   * Tests the authorization part of the flow.
   */
  public function testAuthorization() {

    // Create a user, log the user in, and retry the request.
    $user = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($user);
    $response = $this
      ->authorizationCodeRequest('code');

    // Test the redirect_uri and authorization code.
    $redirect_url_parts = explode('?', $response
      ->getHeader('location')[0]);
    $authorize_redirect = FALSE;
    if ($response
      ->getStatusCode() == 302 && $redirect_url_parts[0] == $this->redirectUri) {
      $authorize_redirect = TRUE;
    }
    $this
      ->assertTrue($authorize_redirect, 'User was properly redirected to the "redirect_uri".');
    $redirect_url_params = $this
      ->getRedirectParams($response);
    $valid_code = (bool) $redirect_url_params['code'];
    $this
      ->assertTrue($valid_code, 'The server returned an authorization code');
    $valid_token = $redirect_url_params['state'] == Crypt::hmacBase64($this->clientId, Settings::getHashSalt());
    $this
      ->assertTrue($valid_token, 'The server returned a valid state');
  }

  /**
   * Tests the implicit flow.
   */
  public function testImplicitFlow() {
    $user = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($user);
    $response = $this
      ->authorizationCodeRequest('token');
    $this
      ->assertEqual($response
      ->getStatusCode(), 302, 'The implicit flow request completed successfully');
    $parameters = $this
      ->getRedirectParams($response, '#');
    $this
      ->assertTokenResponse($parameters, FALSE);

    // We have received an access token. Verify it.
    // See http://drupal.org/node/1958718.
    if (!empty($parameters['access_token'])) {
      $verification_url = $this
        ->buildUrl(new Url('oauth2_server.tokens', [
        'oauth2_server_token' => $parameters['access_token'],
      ]));
      $response = $this
        ->httpGetRequest($verification_url);
      $verification_response = json_decode($response
        ->getBody());
      $this
        ->assertEqual($response
        ->getStatusCode(), 200, 'The provided access token was successfully verified.');
      $this
        ->verbose($verification_response->scope);
      $this
        ->verbose(urldecode($parameters['scope']));
      $this
        ->assertEqual($verification_response->scope, urldecode($parameters['scope']), 'The provided scope matches the scope of the verified access token.');
    }
  }

  /**
   * Tests the "Authorization code" grant type.
   */
  public function testAuthorizationCodeGrantType() {
    $user = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($user);

    // Perform authorization and get the code.
    $response = $this
      ->authorizationCodeRequest('code');
    $redirect_url_params = $this
      ->getRedirectParams($response);
    $authorization_code = $redirect_url_params['code'];
    $token_url = $this
      ->buildUrl(new Url('oauth2_server.token'));
    $data = [
      'grant_type' => 'authorization_code',
      'code' => $authorization_code,
      'redirect_uri' => $this->redirectUri,
    ];
    $response = $this
      ->httpPostRequest($token_url, $data);
    $this
      ->assertEqual($response
      ->getStatusCode(), 200, 'The token request completed successfully');
    $payload = json_decode($response
      ->getBody());
    $this
      ->assertTokenResponse($payload);
  }

  /**
   * Tests the "Client credentials" grant type.
   */
  public function testClientCredentialsGrantType() {
    $user = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($user);
    $token_url = $this
      ->buildUrl(new Url('oauth2_server.token'));
    $data = [
      'grant_type' => 'client_credentials',
    ];
    $response = $this
      ->httpPostRequest($token_url, $data);
    $this
      ->assertEqual($response
      ->getStatusCode(), 200, 'The token request completed successfully');
    $payload = json_decode($response
      ->getBody());
    $this
      ->assertTokenResponse($payload, FALSE);
  }

  /**
   * Tests the "JWT bearer" grant type.
   */
  public function testJwtBearerGrantType() {
    $request_time = \Drupal::time()
      ->getRequestTime();
    $sub_property = \Drupal::config('oauth2_server.oauth')
      ->get('user_sub_property');
    $jwt_util = new Jwt();
    $user = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($user);
    $token_url = $this
      ->buildUrl(new Url('oauth2_server.token'));
    $jwt_data = [
      'iss' => $this->clientId,
      'exp' => $request_time + 1000,
      'iat' => $request_time,
      'sub' => $user->{$sub_property}->value,
      'aud' => $token_url,
      'jti' => '123456',
    ];
    $data = [
      'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      'assertion' => $jwt_util
        ->encode($jwt_data, $this->privateKey, 'RS256'),
    ];
    $response = $this
      ->httpPostRequest($token_url, $data, FALSE);
    $this
      ->assertEqual($response
      ->getStatusCode(), 200, 'The token request completed successfully');
    $payload = json_decode($response
      ->getBody());
    $this
      ->assertTokenResponse($payload, FALSE);
  }

  /**
   * Tests the "User credentials" grant type.
   */
  public function testPasswordGrantType() {
    $response = $this
      ->passwordGrantRequest();
    $this
      ->assertEqual($response
      ->getStatusCode(), 200, 'The token request completed successfully');
    $payload = json_decode($response
      ->getBody());
    $this
      ->assertTokenResponse($payload);
  }

  /**
   * Tests the "Refresh token" grant type.
   */
  public function testRefreshTokenGrantType() {

    // Do a password grant first, in order to get the refresh token.
    $response = $this
      ->passwordGrantRequest();
    $payload = json_decode($response
      ->getBody());
    $refresh_token = $payload->refresh_token;
    $token_url = $this
      ->buildUrl(new Url('oauth2_server.token'));
    $data = [
      'grant_type' => 'refresh_token',
      'refresh_token' => $refresh_token,
    ];
    $response = $this
      ->httpPostRequest($token_url, $data);
    $this
      ->assertEqual($response
      ->getStatusCode(), 200, 'The token request completed successfully');
    $payload = json_decode($response
      ->getBody());

    // The response will include a new refresh_token because
    // always_issue_new_refresh_token is TRUE.
    $this
      ->assertTokenResponse($payload);
  }

  /**
   * Tests scopes.
   */
  public function testScopes() {

    // The default scope returned by oauth2_server_default_scope().
    $response = $this
      ->passwordGrantRequest();
    $payload = json_decode($response
      ->getBody());
    $this
      ->assertEqual($payload->scope, 'admin basic', 'The correct default scope was returned.');

    // A non-existent scope.
    try {
      $this
        ->passwordGrantRequest('invalid_scope');
    } catch (ClientException $e) {
      if ($e
        ->hasResponse()) {
        $this
          ->assertEqual($e
          ->getResponse()
          ->getStatusCode(), 400, 'Invalid scope correctly detected.');
      }
    }

    // A scope forbidden by oauth2_server_scope_access.
    // @see oauth2_server_test_entity_query_alter()
    try {
      $this
        ->passwordGrantRequest('forbidden');
    } catch (ClientException $e) {
      if ($e
        ->hasResponse()) {
        $this
          ->assertEqual($e
          ->getResponse()
          ->getStatusCode(), 400, 'Inaccessible scope correctly detected.');
      }
    }

    // A specific requested scope.
    $response = $this
      ->passwordGrantRequest('admin');
    $payload = json_decode($response
      ->getBody());
    $this
      ->assertEqual($payload->scope, 'admin', 'The correct scope was returned.');
  }

  /**
   * Tests the OpenID Connect authorization code flow.
   */
  public function testOpenIdConnectAuthorizationCodeFlow() {
    $user = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($user);

    // Perform authorization without the offline_access scope.
    // No refresh_token should be returned from the /token endpoint.
    $response = $this
      ->authorizationCodeRequest('code', 'openid');
    $redirect_url_params = $this
      ->getRedirectParams($response);
    $authorization_code = $redirect_url_params['code'];
    $token_url = $this
      ->buildUrl(new Url('oauth2_server.token'));
    $data = [
      'grant_type' => 'authorization_code',
      'code' => $authorization_code,
      'redirect_uri' => $this->redirectUri,
    ];
    $response = $this
      ->httpPostRequest($token_url, $data);
    $this
      ->assertEqual($response
      ->getStatusCode(), 200, 'The token request completed successfully');
    $payload = json_decode($response
      ->getBody());
    $this
      ->assertTokenResponse($payload, FALSE);
    if (!empty($payload->id_token)) {
      $this
        ->assertIdToken($payload->id_token);
    }
    else {
      $this
        ->assertTrue(FALSE, 'The token request returned an id_token.');
    }

    // Perform authorization witho the offline_access scope.
    // A refresh_token should be returned from the /token endpoint.
    $response = $this
      ->authorizationCodeRequest('code', 'openid offline_access');
    $redirect_url_params = $this
      ->getRedirectParams($response);
    $authorization_code = $redirect_url_params['code'];
    $token_url = $this
      ->buildUrl(new Url('oauth2_server.token'));
    $data = [
      'grant_type' => 'authorization_code',
      'code' => $authorization_code,
      'redirect_uri' => $this->redirectUri,
    ];
    $response = $this
      ->httpPostRequest($token_url, $data);
    $this
      ->assertEqual($response
      ->getStatusCode(), 200, 'The token request completed successfully');
    $payload = json_decode($response
      ->getBody());
    $this
      ->assertTokenResponse($payload);
    if (!empty($payload->id_token)) {
      $this
        ->assertIdToken($payload->id_token);
    }
    else {
      $this
        ->assertTrue(FALSE, 'The token request returned an id_token.');
    }
  }

  /**
   * Tests the OpenID Connect implicit flow.
   */
  public function testOpenIdConnectImplicitFlow() {
    $account = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($account);
    $response = $this
      ->authorizationCodeRequest('id_token', 'openid email');
    $this
      ->assertEqual($response
      ->getStatusCode(), 302, 'The "id_token" implicit flow request completed successfully');
    $parameters = $this
      ->getRedirectParams($response, '#');
    if (!empty($parameters['id_token'])) {
      $this
        ->assertIdToken($parameters['id_token'], FALSE, $account);
    }
    else {
      $this
        ->assertTrue(FALSE, 'The token request returned an id_token.');
    }
    $response = $this
      ->authorizationCodeRequest('token id_token', 'openid email profile phone');
    $this
      ->assertEqual($response
      ->getStatusCode(), 302, 'The "token id_token" implicit flow request completed successfully');
    $parameters = $this
      ->getRedirectParams($response, '#');
    $this
      ->assertTokenResponse($parameters, FALSE);
    if (!empty($parameters['id_token'])) {
      $this
        ->assertIdToken($parameters['id_token'], TRUE);
    }
    else {
      $this
        ->assertTrue(FALSE, 'The token request returned an id_token.');
    }
    $account->timezone = 'Europe/London';
    $account
      ->save();

    // Request OpenID Connect user information (claims).
    $query = [
      'access_token' => $parameters['access_token'],
    ];
    $info_url = $this
      ->buildUrl(new Url('oauth2_server.userinfo'), [
      'query' => $query,
    ]);
    $response = $this
      ->httpGetRequest($info_url);
    $payload = json_decode($response
      ->getBody());
    $sub_property = \Drupal::config('oauth2_server.oauth')
      ->get('user_sub_property');
    $expected_claims = [
      'sub' => $account->{$sub_property}->value,
      'email' => $account->mail->value,
      'email_verified' => TRUE,
      'phone_number' => '123456',
      'phone_number_verified' => FALSE,
      'preferred_username' => $account->name->value,
      'name' => $account
        ->label(),
      'zoneinfo' => $account->timezone->value,
    ];
    foreach ($expected_claims as $claim => $expected_value) {
      $this
        ->assertEqual($payload->{$claim}, $expected_value, 'The UserInfo endpoint returned a valid "' . $claim . '" claim');
    }
  }

  /**
   * Tests that the OpenID Connect 'sub' property affects user info 'sub' claim.
   */
  public function testOpenIdConnectNonDefaultSub() {
    $this
      ->config('oauth2_server.oauth')
      ->set('user_sub_property', 'name')
      ->save();
    $response = $this
      ->passwordGrantRequest('openid');
    $payload = json_decode($response
      ->getBody());
    $access_token = $payload->access_token;
    $query = [
      'access_token' => $access_token,
    ];
    $info_url = $this
      ->buildUrl(new Url('oauth2_server.userinfo'), [
      'query' => $query,
    ]);
    $response = $this
      ->httpGetRequest($info_url);
    $payload = json_decode($response
      ->getBody(), TRUE);
    $this
      ->assertEqual($this->loggedInUser->name->value, $payload['sub'], 'The UserInfo "sub" is now the user\'s name.');
  }

  /**
   * Tests that the OpenID Connect 'sub' property affects ID token 'sub' claim.
   */
  public function testOpenIdConnectNonDefaultSubInIdToken() {
    $this
      ->config('oauth2_server.oauth')
      ->set('user_sub_property', 'name')
      ->save();

    // This is the authorization code grant type flow.
    $user = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($user);
    $response = $this
      ->authorizationCodeRequest('code', 'openid offline_access');
    $parameters = $this
      ->getRedirectParams($response);
    $authorization_code = $parameters['code'];

    // Get tokens using the authorization code.
    $token_url = $this
      ->buildUrl(new Url('oauth2_server.token'));
    $data = [
      'grant_type' => 'authorization_code',
      'code' => $authorization_code,
      'redirect_uri' => $this->redirectUri,
    ];
    $response = $this
      ->httpPostRequest($token_url, $data);
    $payload = json_decode($response
      ->getBody());
    $parts = explode('.', $payload->id_token);
    $claims = json_decode(Utility::base64urlDecode($parts[1]), TRUE);
    $this
      ->assertEqual($this->loggedInUser->name->value, $claims['sub'], 'The ID token "sub" is now the user\'s name.');
  }

  /**
   * Tests crypto tokens.
   */
  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.');
  }

  /**
   * Tests resource requests.
   */
  public function testResourceRequests() {
    $response = $this
      ->passwordGrantRequest('admin');
    $payload = json_decode($response
      ->getBody());
    $access_token = $payload->access_token;

    // Check resource access with no access token.
    $resource_url = $this
      ->buildUrl(new Url('oauth2_server_test.resource', [
      'oauth2_server_scope' => 'admin',
    ]));
    try {
      $this
        ->httpGetRequest($resource_url);
    } catch (ClientException $e) {
      if ($e
        ->hasResponse()) {
        $this
          ->assertEqual($e
          ->getResponse()
          ->getStatusCode(), 401, 'Missing access token correctly detected.');
      }
    }

    // Check resource access with an insufficient scope.
    $query = [
      'access_token' => $access_token,
    ];
    $resource_url = $this
      ->buildUrl(new Url('oauth2_server_test.resource', [
      'oauth2_server_scope' => 'forbidden',
    ], [
      'query' => $query,
    ]));
    try {
      $this
        ->httpGetRequest($resource_url);
    } catch (ClientException $e) {
      if ($e
        ->hasResponse()) {
        $this
          ->assertEqual($e
          ->getResponse()
          ->getStatusCode(), 403, 'Insufficient scope correctly detected.');
      }
    }

    // @fixme Check resource access with the access token in the url.

    //$query = [

    //  'access_token' => $access_token,

    //];

    //$resource_url = $this->buildUrl(new Url('oauth2_server_test.resource', ['oauth2_server_scope' => 'admin'], ['query' => $query]));

    //$response = $this->httpGetRequest($resource_url);

    //$this->assertEqual($response->getStatusCode(), 200, 'Access token in the URL correctly detected.');

    // @fixme Check resource access with the access token in the header.

    //$resource_url = $this->buildUrl(new Url('oauth2_server_test.resource', ['oauth2_server_scope' => 'admin']));

    //$options = [

    //  'headers' => [
    //    'Authorization' =>  'Bearer ' . $access_token,
    //  ],

    //];

    //$response = $this->httpGetRequest($resource_url, $options);

    //$this->assertEqual($response->getStatusCode(), 200, 'Access token in the header correctly detected.');
  }

  /**
   * Test that access is denied when using a token for a blocked user.
   */
  public function testBlockedUserTokenFails() {

    // Get a normal access token for a normal user.
    $response = $this
      ->passwordGrantRequest('admin');
    $payload = json_decode($response
      ->getBody());
    $access_token = $payload->access_token;

    // @fixme Check resource access while the user is active.
    $resource_url = $this
      ->buildUrl(new Url('oauth2_server_test.resource', [
      'oauth2_server_scope' => 'admin',
    ]));
    $options = [
      'headers' => [
        'Authorization' => 'Bearer ' . $access_token,
      ],
    ];

    //$response = $this->httpGetRequest($resource_url, $options);

    //$this->assertEqual($response->getStatusCode(), 200, 'An active user is correctly authenticated.');

    // Block the user.
    $this->loggedInUser->status = 0;
    $this->loggedInUser
      ->save();

    // Check resource access while the user is blocked.
    try {
      $this
        ->httpGetRequest($resource_url, $options);
    } catch (ClientException $e) {
      if ($e
        ->hasResponse()) {
        $this
          ->assertEqual($e
          ->getResponse()
          ->getStatusCode(), 403, 'A blocked user is denied access with 403 Forbidden.');
      }
    }
  }

  /**
   * Assert that the given token response has the expected values.
   *
   * @param array|object $payload
   *   The response payload (either an object decoded from a json string or the
   *   prepared query string as array).
   * @param bool $has_refresh_token
   *   A boolean indicating whether this response should have a refresh token.
   */
  protected function assertTokenResponse($payload, $has_refresh_token = TRUE) {

    // Make sure we have an array.
    $payload = (array) $payload;
    $this
      ->assertArrayHasKey('access_token', $payload, 'The "access token" value is present in the return values');
    $this
      ->assertArrayHasKey('expires_in', $payload, 'The "expires_in" value is present in the return values');
    $this
      ->assertArrayHasKey('token_type', $payload, 'The "token_type" value is present in the return values');
    $this
      ->assertArrayHasKey('scope', $payload, 'The "scope" value is present in the return values');
    if ($has_refresh_token) {
      $this
        ->assertArrayHasKey('refresh_token', $payload, 'The "refresh_token" value is present in the return values');
    }
  }

  /**
   * Assert that the given id_token response has the expected values.
   *
   * @param string $id_token
   *   The id_token.
   * @param bool $has_at_hash
   *   Whether the token is supposed to contain the at_hash claim.
   * @param \Drupal\user\Entity\User|null $account
   *   The account of the authenticated user, if the id_token is supposed
   *   to contain user claims.
   */
  protected function assertIdToken($id_token, $has_at_hash = FALSE, $account = NULL) {
    $parts = explode('.', $id_token);
    [
      $headerb64,
      $claims64,
      $signatureb64,
    ] = $parts;
    $claims = json_decode(Utility::base64urlDecode($claims64), TRUE);
    $signature = Utility::base64urlDecode($signatureb64);
    $payload = utf8_decode($headerb64 . '.' . $claims64);
    $verified = (bool) openssl_verify($payload, $signature, $this->publicKey, 'sha256');
    $this
      ->assertTrue($verified, 'The id_token has a valid signature.');
    $this
      ->assertArrayHasKey('iss', $claims, 'The id_token contains an "iss" claim.');
    $this
      ->assertArrayHasKey('sub', $claims, 'The id_token contains a "sub" claim.');
    $this
      ->assertArrayHasKey('aud', $claims, 'The id_token contains an "aud" claim.');
    $this
      ->assertArrayHasKey('iat', $claims, 'The id_token contains an "iat" claim.');
    $this
      ->assertArrayHasKey('exp', $claims, 'The id_token contains an "exp" claim.');
    $this
      ->assertArrayHasKey('auth_time', $claims, 'The id_token contains an "auth_time" claim.');
    $this
      ->assertArrayHasKey('nonce', $claims, 'The id_token contains a "nonce" claim');
    if ($has_at_hash) {
      $this
        ->assertArrayHasKey('at_hash', $claims, 'The id_token contains an "at_hash" claim.');
    }
    if ($account) {
      $this
        ->assertArrayHasKey('email', $claims, 'The id_token contains an "email" claim.');
      $this
        ->assertArrayHasKey('email_verified', $claims, 'The id_token contains an "email_verified" claim.');
    }
    $this
      ->assertEqual($claims['aud'], $this->clientId, 'The id_token "aud" claim contains the expected client_id.');
    $this
      ->assertEqual($claims['nonce'], 'test', 'The id_token "nonce" claim contains the expected nonce.');
    if ($account) {
      $this
        ->assertEqual($claims['email'], $account->mail
        ->getValue()[0]['value']);
    }
  }

  /**
   * Performs an authorization request and returns it.
   *
   * Used to test authorization, the implicit flow, and the authorization_code
   * grant type.
   *
   * @param string $response_type
   *   The response type string.
   * @param string|null $scope
   *   The scope string.
   *
   * @return \Psr\Http\Message\ResponseInterface
   *   A response object.
   *
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  protected function authorizationCodeRequest($response_type, $scope = NULL) {
    $query = [
      'response_type' => $response_type,
      'client_id' => $this->clientId,
      'state' => Crypt::hmacBase64($this->clientId, Settings::getHashSalt()),
      'redirect_uri' => $this->redirectUri,
      // OpenID Connect requests require a nonce. Others ignore it.
      'nonce' => 'test',
    ];
    if ($scope) {
      $query['scope'] = $scope;
    }
    $url = new Url('oauth2_server.authorize');
    $cookieJar = $this
      ->getSessionCookies();
    $options = [
      'allow_redirects' => FALSE,
      'cookies' => $cookieJar,
      'query' => $query,
    ];
    return $this
      ->getHttpClient()
      ->request('GET', $url
      ->setAbsolute()
      ->toString(), $options);
  }

  /**
   * Performs a password grant request and returns it.
   *
   * Used to test the grant itself, as well as a helper for other tests
   * (since it's a fast way of getting an access token).
   *
   * @param string|null $scope
   *   An optional scope to request.
   *
   * @return \Psr\Http\Message\ResponseInterface
   *   The return value of $this->httpRequest().
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  protected function passwordGrantRequest($scope = NULL) {
    $user = $this
      ->drupalCreateUser([
      'use oauth2 server',
    ]);
    $this
      ->drupalLogin($user);
    $token_url = $this
      ->buildUrl(new Url('oauth2_server.token'));
    $data = [
      'grant_type' => 'password',
      'username' => $user->name
        ->getValue()[0]['value'],
      'password' => $user->pass_raw,
    ];
    if ($scope) {
      $data['scope'] = $scope;
    }
    return $this
      ->httpPostRequest($token_url, $data);
  }

  /**
   * Get redirect parameters.
   *
   * @param \Psr\Http\Message\ResponseInterface $response
   *   A response message object.
   * @param string $explode
   *   A string to explode on.
   *
   * @return array
   *   An associative array of redirect parameters.
   */
  public function getRedirectParams(ResponseInterface $response, $explode = '?') {
    $redirect_url_parts = explode($explode, $response
      ->getHeader('location')[0]);
    $result = [];
    parse_str($redirect_url_parts[1], $result);
    return $result;
  }

  /**
   * Perform a GET request.
   *
   * @param string $url
   *   A Url object.
   * @param array $options
   *   An options array.
   *
   * @return \Psr\Http\Message\ResponseInterface
   *   The response object.
   *
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function httpGetRequest($url, array $options = []) {
    $cookieJar = $this
      ->getSessionCookies();
    $options += [
      'cookies' => $cookieJar,
      'allow_redirects' => FALSE,
      'debug' => FALSE,
    ];
    return $this
      ->getHttpClient()
      ->request('GET', $url, $options);
  }

  /**
   * Perform a POST request.
   *
   * @param string $url
   *   A Url object.
   * @param array $data
   *   A data array.
   * @param bool $authorization
   *   Whether to authorize the request.
   *
   * @return \Psr\Http\Message\ResponseInterface
   *   The response object.
   *
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function httpPostRequest($url, array $data = [], $authorization = TRUE) {
    $cookieJar = $this
      ->getSessionCookies();
    $options = [
      'cookies' => $cookieJar,
      'allow_redirects' => FALSE,
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/x-www-form-urlencoded',
      ],
      'form_params' => $data,
      'debug' => FALSE,
    ];
    if ($authorization) {
      $options['headers']['Authorization'] = 'Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret);
    }
    return $this
      ->getHttpClient()
      ->request('POST', $url, $options);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssertLegacyTrait::assert Deprecated protected function
AssertLegacyTrait::assertCacheTag Deprecated protected function Asserts whether an expected cache tag was present in the last response.
AssertLegacyTrait::assertElementNotPresent Deprecated protected function Asserts that the element with the given CSS selector is not present.
AssertLegacyTrait::assertElementPresent Deprecated protected function Asserts that the element with the given CSS selector is present.
AssertLegacyTrait::assertEqual Deprecated protected function
AssertLegacyTrait::assertEscaped Deprecated protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertLegacyTrait::assertField Deprecated protected function Asserts that a field exists with the given name or ID.
AssertLegacyTrait::assertFieldById Deprecated protected function Asserts that a field exists with the given ID and value.
AssertLegacyTrait::assertFieldByName Deprecated protected function Asserts that a field exists with the given name and value.
AssertLegacyTrait::assertFieldByXPath Deprecated protected function Asserts that a field exists in the current page by the given XPath.
AssertLegacyTrait::assertFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is checked.
AssertLegacyTrait::assertFieldsByValue Deprecated protected function Asserts that a field exists in the current page with a given Xpath result.
AssertLegacyTrait::assertHeader Deprecated protected function Checks that current response header equals value.
AssertLegacyTrait::assertIdentical Deprecated protected function
AssertLegacyTrait::assertIdenticalObject Deprecated protected function
AssertLegacyTrait::assertLink Deprecated protected function Passes if a link with the specified label is found.
AssertLegacyTrait::assertLinkByHref Deprecated protected function Passes if a link containing a given href (part) is found.
AssertLegacyTrait::assertNoCacheTag Deprecated protected function Asserts whether an expected cache tag was absent in the last response.
AssertLegacyTrait::assertNoEscaped Deprecated protected function Passes if the raw text is not found escaped on the loaded page.
AssertLegacyTrait::assertNoField Deprecated protected function Asserts that a field does NOT exist with the given name or ID.
AssertLegacyTrait::assertNoFieldById Deprecated protected function Asserts that a field does not exist with the given ID and value.
AssertLegacyTrait::assertNoFieldByName Deprecated protected function Asserts that a field does not exist with the given name and value.
AssertLegacyTrait::assertNoFieldByXPath Deprecated protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertLegacyTrait::assertNoFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is not checked.
AssertLegacyTrait::assertNoLink Deprecated protected function Passes if a link with the specified label is not found.
AssertLegacyTrait::assertNoLinkByHref Deprecated protected function Passes if a link containing a given href (part) is not found.
AssertLegacyTrait::assertNoOption Deprecated protected function Asserts that a select option does NOT exist in the current page.
AssertLegacyTrait::assertNoPattern Deprecated protected function Triggers a pass if the Perl regex pattern is not found in the raw content.
AssertLegacyTrait::assertNoRaw Deprecated protected function Passes if the raw text IS not found on the loaded page, fail otherwise.
AssertLegacyTrait::assertNotEqual Deprecated protected function
AssertLegacyTrait::assertNoText Deprecated protected function Passes if the page (with HTML stripped) does not contains the text.
AssertLegacyTrait::assertNotIdentical Deprecated protected function
AssertLegacyTrait::assertNoUniqueText Deprecated protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertLegacyTrait::assertOption Deprecated protected function Asserts that a select option in the current page exists.
AssertLegacyTrait::assertOptionByText Deprecated protected function Asserts that a select option with the visible text exists.
AssertLegacyTrait::assertOptionSelected Deprecated protected function Asserts that a select option in the current page is checked.
AssertLegacyTrait::assertPattern Deprecated protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertLegacyTrait::assertRaw Deprecated protected function Passes if the raw text IS found on the loaded page, fail otherwise.
AssertLegacyTrait::assertResponse Deprecated protected function Asserts the page responds with the specified response code.
AssertLegacyTrait::assertText Deprecated protected function Passes if the page (with HTML stripped) contains the text.
AssertLegacyTrait::assertTextHelper Deprecated protected function Helper for assertText and assertNoText.
AssertLegacyTrait::assertTitle Deprecated protected function Pass if the page title is the given string.
AssertLegacyTrait::assertUniqueText Deprecated protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertLegacyTrait::assertUrl Deprecated protected function Passes if the internal browser's URL matches the given path.
AssertLegacyTrait::buildXPathQuery Deprecated protected function Builds an XPath query.
AssertLegacyTrait::constructFieldXpath Deprecated protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertLegacyTrait::getAllOptions Deprecated protected function Get all option elements, including nested options, in a select.
AssertLegacyTrait::getRawContent Deprecated protected function Gets the current raw content.
AssertLegacyTrait::pass Deprecated protected function
AssertLegacyTrait::verbose Deprecated protected function
BlockCreationTrait::placeBlock protected function Creates a block instance based on default settings. Aliased as: drupalPlaceBlock
BrowserHtmlDebugTrait::$htmlOutputBaseUrl protected property The Base URI to use for links to the output files.
BrowserHtmlDebugTrait::$htmlOutputClassName protected property Class name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounter protected property Counter for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputCounterStorage protected property Counter storage for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputDirectory protected property Directory name for HTML output logging.
BrowserHtmlDebugTrait::$htmlOutputEnabled protected property HTML output output enabled.
BrowserHtmlDebugTrait::$htmlOutputFile protected property The file name to write the list of URLs to.
BrowserHtmlDebugTrait::$htmlOutputTestId protected property HTML output test ID.
BrowserHtmlDebugTrait::formatHtmlOutputHeaders protected function Formats HTTP headers as string for HTML output logging.
BrowserHtmlDebugTrait::getHtmlOutputHeaders protected function Returns headers in HTML output format. 1
BrowserHtmlDebugTrait::getResponseLogHandler protected function Provides a Guzzle middleware handler to log every response received.
BrowserHtmlDebugTrait::htmlOutput protected function Logs a HTML output message in a text file.
BrowserHtmlDebugTrait::initBrowserOutputFile protected function Creates the directory to store browser output.
BrowserTestBase::$baseUrl protected property The base URL.
BrowserTestBase::$configImporter protected property The config importer that can be used in a test.
BrowserTestBase::$customTranslations protected property An array of custom translations suitable for drupal_rewrite_settings().
BrowserTestBase::$databasePrefix protected property The database prefix of this test run.
BrowserTestBase::$mink protected property Mink session manager.
BrowserTestBase::$minkDefaultDriverArgs protected property Mink default driver params.
BrowserTestBase::$minkDefaultDriverClass protected property Mink class for the default driver to use. 1
BrowserTestBase::$originalContainer protected property The original container.
BrowserTestBase::$originalShutdownCallbacks protected property The original array of shutdown function callbacks.
BrowserTestBase::$preserveGlobalState protected property
BrowserTestBase::$profile protected property The profile to install as a basis for testing. 39
BrowserTestBase::$root protected property The app root.
BrowserTestBase::$runTestInSeparateProcess protected property Browser tests are run in separate processes to prevent collisions between code that may be loaded by tests.
BrowserTestBase::$timeLimit protected property Time limit in seconds for the test.
BrowserTestBase::$translationFilesDirectory protected property The translation file directory for the test environment.
BrowserTestBase::cleanupEnvironment protected function Clean up the Simpletest environment.
BrowserTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
BrowserTestBase::drupalGetHeader Deprecated protected function Gets the value of an HTTP response header.
BrowserTestBase::filePreDeleteCallback public static function Ensures test files are deletable.
BrowserTestBase::getDefaultDriverInstance protected function Gets an instance of the default Mink driver.
BrowserTestBase::getDrupalSettings protected function Gets the JavaScript drupalSettings variable for the currently-loaded page. 1
BrowserTestBase::getHttpClient protected function Obtain the HTTP client for the system under test.
BrowserTestBase::getMinkDriverArgs protected function Get the Mink driver args from an environment variable, if it is set. Can be overridden in a derived class so it is possible to use a different value for a subset of tests, e.g. the JavaScript tests. 1
BrowserTestBase::getOptions protected function Helper function to get the options of select field.
BrowserTestBase::getSession public function Returns Mink session.
BrowserTestBase::getSessionCookies protected function Get session cookies from current session.
BrowserTestBase::getTestMethodCaller protected function Retrieves the current calling line in the class under test. Overrides BrowserHtmlDebugTrait::getTestMethodCaller
BrowserTestBase::initFrontPage protected function Visits the front page when initializing Mink. 3
BrowserTestBase::initMink protected function Initializes Mink sessions. 1
BrowserTestBase::installDrupal public function Installs Drupal into the Simpletest site. 1
BrowserTestBase::registerSessions protected function Registers additional Mink sessions.
BrowserTestBase::setUpAppRoot protected function Sets up the root application path.
BrowserTestBase::setUpBeforeClass public static function 1
BrowserTestBase::tearDown protected function 3
BrowserTestBase::translatePostValues protected function Transforms a nested array into a flat array suitable for submitForm().
BrowserTestBase::xpath protected function Performs an xpath search on the contents of the internal browser.
BrowserTestBase::__sleep public function Prevents serializing any properties.
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
ContentTypeCreationTrait::createContentType protected function Creates a custom content type based on default settings. Aliased as: drupalCreateContentType 1
ExtensionListTestTrait::getModulePath protected function Gets the path for the specified module.
ExtensionListTestTrait::getThemePath protected function Gets the path for the specified theme.
FunctionalTestSetupTrait::$apcuEnsureUniquePrefix protected property The flag to set 'apcu_ensure_unique_prefix' setting. 1
FunctionalTestSetupTrait::$classLoader protected property The class loader to use for installation and initialization of setup.
FunctionalTestSetupTrait::$rootUser protected property The "#1" admin user.
FunctionalTestSetupTrait::doInstall protected function Execute the non-interactive installer. 1
FunctionalTestSetupTrait::getDatabaseTypes protected function Returns all supported database driver installer objects.
FunctionalTestSetupTrait::initConfig protected function Initialize various configurations post-installation. 1
FunctionalTestSetupTrait::initKernel protected function Initializes the kernel after installation.
FunctionalTestSetupTrait::initSettings protected function Initialize settings created during install.
FunctionalTestSetupTrait::initUserSession protected function Initializes user 1 for the site to be installed.
FunctionalTestSetupTrait::installDefaultThemeFromClassProperty protected function Installs the default theme defined by `static::$defaultTheme` when needed.
FunctionalTestSetupTrait::installModulesFromClassProperty protected function Install modules defined by `static::$modules`. 1
FunctionalTestSetupTrait::installParameters protected function Returns the parameters that will be used when Simpletest installs Drupal. 9
FunctionalTestSetupTrait::prepareEnvironment protected function Prepares the current environment for running the test. 20
FunctionalTestSetupTrait::prepareRequestForGenerator protected function Creates a mock request and sets it on the generator.
FunctionalTestSetupTrait::prepareSettings protected function Prepares site settings and services before installation. 2
FunctionalTestSetupTrait::rebuildAll protected function Resets and rebuilds the environment after setup.
FunctionalTestSetupTrait::rebuildContainer protected function Rebuilds \Drupal::getContainer().
FunctionalTestSetupTrait::resetAll protected function Resets all data structures after having enabled new modules.
FunctionalTestSetupTrait::setContainerParameter protected function Changes parameters in the services.yml file.
FunctionalTestSetupTrait::setupBaseUrl protected function Sets up the base URL based upon the environment variable.
FunctionalTestSetupTrait::writeSettings protected function Rewrites the settings.php file of the test site. 1
NodeCreationTrait::createNode protected function Creates a node based on default settings. Aliased as: drupalCreateNode
NodeCreationTrait::getNodeByTitle public function Get a node from the database based on its title. Aliased as: drupalGetNodeByTitle
OAuth2ServerTest::$clientId protected property The client key of the test client.
OAuth2ServerTest::$clientSecret protected property The client secret of the test client.
OAuth2ServerTest::$defaultTheme protected property The theme to install as the default for testing. Overrides BrowserTestBase::$defaultTheme
OAuth2ServerTest::$modules public static property Modules to enable. Overrides BrowserTestBase::$modules
OAuth2ServerTest::$privateKey protected property The private key used for all tests with encryption.
OAuth2ServerTest::$publicKey protected property The public key X.509 certificate used for all tests with encryption.
OAuth2ServerTest::$redirectUri protected property The redirect uri used on multiple locations.
OAuth2ServerTest::assertIdToken protected function Assert that the given id_token response has the expected values.
OAuth2ServerTest::assertTokenResponse protected function Assert that the given token response has the expected values.
OAuth2ServerTest::authorizationCodeRequest protected function Performs an authorization request and returns it.
OAuth2ServerTest::getRedirectParams public function Get redirect parameters.
OAuth2ServerTest::httpGetRequest public function Perform a GET request.
OAuth2ServerTest::httpPostRequest public function Perform a POST request.
OAuth2ServerTest::passwordGrantRequest protected function Performs a password grant request and returns it.
OAuth2ServerTest::setUp protected function Overrides BrowserTestBase::setUp
OAuth2ServerTest::testAuthorization public function Tests the authorization part of the flow.
OAuth2ServerTest::testAuthorizationCodeGrantType public function Tests the "Authorization code" grant type.
OAuth2ServerTest::testBlockedUserTokenFails public function Test that access is denied when using a token for a blocked user.
OAuth2ServerTest::testClientCredentialsGrantType public function Tests the "Client credentials" grant type.
OAuth2ServerTest::testCryptoTokens public function Tests crypto tokens.
OAuth2ServerTest::testImplicitFlow public function Tests the implicit flow.
OAuth2ServerTest::testJwtBearerGrantType public function Tests the "JWT bearer" grant type.
OAuth2ServerTest::testOpenIdConnectAuthorizationCodeFlow public function Tests the OpenID Connect authorization code flow.
OAuth2ServerTest::testOpenIdConnectImplicitFlow public function Tests the OpenID Connect implicit flow.
OAuth2ServerTest::testOpenIdConnectNonDefaultSub public function Tests that the OpenID Connect 'sub' property affects user info 'sub' claim.
OAuth2ServerTest::testOpenIdConnectNonDefaultSubInIdToken public function Tests that the OpenID Connect 'sub' property affects ID token 'sub' claim.
OAuth2ServerTest::testPasswordGrantType public function Tests the "User credentials" grant type.
OAuth2ServerTest::testRefreshTokenGrantType public function Tests the "Refresh token" grant type.
OAuth2ServerTest::testResourceRequests public function Tests resource requests.
OAuth2ServerTest::testScopes public function Tests scopes.
PhpUnitWarnings::$deprecationWarnings private static property Deprecation warnings from PHPUnit to raise with @trigger_error().
PhpUnitWarnings::addWarning public function Converts PHPUnit deprecation warnings to E_USER_DEPRECATED.
RandomGeneratorTrait::$randomGenerator protected property The random generator.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers. 1
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate public function Callback for random string validation.
RefreshVariablesTrait::refreshVariables protected function Refreshes in-memory configuration and state information. 1
SessionTestTrait::$sessionName protected property The name of the session cookie.
SessionTestTrait::generateSessionName protected function Generates a session cookie name.
SessionTestTrait::getSessionName protected function Returns the session name in use on the child site.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
TestRequirementsTrait::checkModuleRequirements private function Checks missing module requirements.
TestRequirementsTrait::checkRequirements protected function Check module requirements for the Drupal use case. 1
TestRequirementsTrait::getDrupalRoot protected static function Returns the Drupal root directory.
TestSetupTrait::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking.
TestSetupTrait::$container protected property The dependency injection container used in the test.
TestSetupTrait::$kernel protected property The DrupalKernel instance used in the test.
TestSetupTrait::$originalSite protected property The site directory of the original parent site.
TestSetupTrait::$privateFilesDirectory protected property The private file directory for the test environment.
TestSetupTrait::$publicFilesDirectory protected property The public file directory for the test environment.
TestSetupTrait::$siteDirectory protected property The site directory of this test run.
TestSetupTrait::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 1
TestSetupTrait::$tempFilesDirectory protected property The temporary file directory for the test environment.
TestSetupTrait::$testId protected property The test run ID.
TestSetupTrait::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
TestSetupTrait::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
TestSetupTrait::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
TestSetupTrait::prepareDatabasePrefix protected function Generates a database prefix for running tests. 1
UiHelperTrait::$loggedInUser protected property The current user logged in using the Mink controlled browser.
UiHelperTrait::$maximumMetaRefreshCount protected property The number of meta refresh redirects to follow, or NULL if unlimited.
UiHelperTrait::$metaRefreshCount protected property The number of meta refresh redirects followed during ::drupalGet().
UiHelperTrait::assertSession public function Returns WebAssert object. 1
UiHelperTrait::buildUrl protected function Builds an absolute URL from a system path or a URL object.
UiHelperTrait::checkForMetaRefresh protected function Checks for meta refresh tag and if found call drupalGet() recursively.
UiHelperTrait::click protected function Clicks the element with the given CSS selector.
UiHelperTrait::clickLink protected function Follows a link by complete name.
UiHelperTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
UiHelperTrait::cssSelectToXpath protected function Translates a CSS expression to its XPath equivalent.
UiHelperTrait::drupalGet protected function Retrieves a Drupal path or an absolute path. 2
UiHelperTrait::drupalLogin protected function Logs in a user using the Mink controlled browser.
UiHelperTrait::drupalLogout protected function Logs a user out of the Mink controlled browser and confirms.
UiHelperTrait::drupalPostForm Deprecated protected function Executes a form submission.
UiHelperTrait::drupalUserIsLoggedIn protected function Returns whether a given user account is logged in.
UiHelperTrait::getAbsoluteUrl protected function Takes a path and returns an absolute path.
UiHelperTrait::getTextContent protected function Retrieves the plain-text content from the current page.
UiHelperTrait::getUrl protected function Get the current URL from the browser.
UiHelperTrait::isTestUsingGuzzleClient protected function Determines if test is using DrupalTestBrowser.
UiHelperTrait::prepareRequest protected function Prepare for a request to testing site. 1
UiHelperTrait::submitForm protected function Fills and submits a form.
UserCreationTrait::checkPermissions protected function Checks whether a given list of permission names is valid.
UserCreationTrait::createAdminRole protected function Creates an administrative role.
UserCreationTrait::createRole protected function Creates a role with specified permissions. Aliased as: drupalCreateRole
UserCreationTrait::createUser protected function Create a user with a given set of permissions. Aliased as: drupalCreateUser
UserCreationTrait::grantPermissions protected function Grant permissions to a user role.
UserCreationTrait::setCurrentUser protected function Switch the current logged in user.
UserCreationTrait::setUpCurrentUser protected function Creates a random user account and sets it as current user.
XdebugRequestTrait::extractCookiesFromRequest protected function Adds xdebug cookies, from request setup.