You are here

function oauth2_server_check_access in OAuth2 Server 7

Check access for the passed server and scope.

Parameters

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

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

Return value

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

3 calls to oauth2_server_check_access()
OAuth2ServerRestfulAuthentication::authenticate in plugins/authentication/OAuth2ServerRestfulAuthentication.class.php
Authenticate the request by trying to match a user.
oauth2_server_services_authenticate_call in includes/oauth2_server.services_auth.inc
Services authentication "authenticate_call" callback.
oauth2_server_verify_access in ./oauth2_server.module
Verifies access for the passed server and scope.

File

./oauth2_server.module, line 1052
Provides OAuth2 server functionality.

Code

function oauth2_server_check_access($server_name, $scope = NULL) {

  // Disable the page cache to ensure access to the resource is not granted
  // longer than allowed.
  drupal_page_is_cacheable(FALSE);
  $server = oauth2_server_load($server_name);
  $oauth2_server = oauth2_server_start($server);
  $response = new OAuth2\Response();
  $token = $oauth2_server
    ->getAccessTokenData(OAuth2\Request::createFromGlobals(), $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->name) {
    $response
      ->setError(401, 'invalid_grant', 'The access token provided is invalid');
    $response
      ->addHttpHeaders(array(
      '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 Drupal\oauth2_server\Scope($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(array(
      'WWW-Authenticate' => sprintf('%s, realm="%s", scope="%s"', 'bearer', 'Service', $scope),
    ));
    return $response;
  }
  return $token;
}