You are here

public static function Utility::checkAccess in OAuth2 Server 8

Same name and namespace in other branches
  1. 2.0.x src/Utility.php \Drupal\oauth2_server\Utility::checkAccess()

Check access for the passed server and scope.

Parameters

string $server_name: The name of the server for which access should be verified.

string|null $scope: An optional string of space-separated scopes to check.

Return value

\OAuth2\ResponseInterface|array A valid access token if found, otherwise an \OAuth2\Response object containing an appropriate response message and status code.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

1 call to Utility::checkAccess()
ResourceController::test in tests/modules/oauth2_server_test/src/Controller/ResourceController.php
Test resource.

File

src/Utility.php, line 302

Class

Utility
Contains utility methods for the OAuth2 Server.

Namespace

Drupal\oauth2_server

Code

public static function checkAccess($server_name, $scope = NULL) {

  /** @var \Drupal\oauth2_server\ServerInterface $server */
  $server = \Drupal::entityTypeManager()
    ->getStorage('oauth2_server')
    ->load($server_name);
  $storage = \Drupal::service('oauth2_server.storage');
  $oauth2_server = Utility::startServer($server, $storage);
  $response = new BridgeResponse();
  $request = \Drupal::requestStack()
    ->getCurrentRequest();
  $bridgeRequest = BridgeRequest::createFromRequest($request);
  $token = $oauth2_server
    ->getAccessTokenData($bridgeRequest, $response);

  // If there's no token, that means validation failed. Stop here.
  if (!$token) {
    return $response;
  }

  // Make sure that the token we have matches our server.
  if ($token['server'] != $server
    ->id()) {
    $response
      ->setError(401, 'invalid_grant', 'The access token provided is invalid');
    $response
      ->addHttpHeaders([
      'WWW-Authenticate' => sprintf('%s, realm="%s", scope="%s"', 'bearer', 'Service', $scope),
    ]);
    return $response;
  }

  // Check scope, if provided. If token doesn't have a scope, it's null/empty,
  // or it's insufficient, throw an error.
  $scope_util = new ScopeUtility($server);
  if ($scope && (!isset($token["scope"]) || !$token["scope"] || !$scope_util
    ->checkScope($scope, $token["scope"]))) {
    $response
      ->setError(401, 'insufficient_scope', 'The request requires higher privileges than provided by the access token');
    $response
      ->addHttpHeaders([
      'WWW-Authenticate' => sprintf('%s, realm="%s", scope="%s"', 'bearer', 'Service', $scope),
    ]);
    return $response;
  }
  return $token;
}