Get client credentials for requests.

@param mixed $scope Scopes to request for this token from the server.
@return array Response from the server with the tokens, we also set it into this object.
480306
public function clientCredentials($scope = 'public')
    {
        if (is_array($scope)) {
            $scope = implode(' ', $scope);
        }

        $token_response = $this->request(self::CLIENT_CREDENTIALS_TOKEN_ENDPOINT, array(
            'grant_type' => 'client_credentials',
            'scope' => $scope
        ), "POST", false);

        return $token_response;
    }
556141
public function requestClientCredentials($options = array()) {
        $options = array_merge(array(
            'scope' => '',
        ), $options);

        $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array(
            'client_id' => $this->getClientId(),
            'client_secret' => $this->getClientSecret(),
            'grant_type' => 'client_credentials',
            'scope' => $options['scope'],
        ));
        $result = $res->getBody();

        $token = null;
        if ($result && $result = json_decode($result, true)) {
            if (!empty($result['error'])) {
                throw new Exception($result['error_description']);
            }

            if (!empty($result['access_token'])) {
                $this->accessToken = $token = $result['access_token'];
            }
        }

        if (empty($token)) {
            throw new InvalidTokenException('token not available.');
        }

        return $token;
    }
1203047
public function authentication(Request $request, array $credentials)
    {
        if (!isset($credentials['username'], $credentials['password'])) {
            return $request;
        }
        if (!isset($credentials['realm'])) {
            $credentials = $this->_getServerInfo($request, $credentials);
        }
        if (!isset($credentials['realm'])) {
            return $request;
        }
        $value = $this->_generateHeader($request, $credentials);

        return $request->withHeader('Authorization', $value);
    }
24900
public function getScopeFilter($scope)
	{
		$filters = $this->getFilters();

		return isset($filters[$scope]) ? $filters[$scope] : null;
	}
145840
public function retrieveTokenRequest(array $scope = array()) {
    $parameters = array(
      'oauth_callback' => $this->getCallbackUrl()
    );

    $requestUrl = self::_URL_REQUEST;

    if (!empty($scope)) {
        $requestUrl .= '?scope=' . implode('+', $scope);
    }

    $response = $this->fetch(self::_METHOD_TOKENS, $requestUrl, NULL, $parameters);
    parse_str($response['linkedin'], $response['linkedin']);
    
    /**
	   * Check for successful request (a 200 response from LinkedIn server) 
	   * per the documentation linked in method comments above.
	   */
    if(($response['info']['http_code'] == 200) && (array_key_exists('oauth_callback_confirmed', $response['linkedin'])) && ($response['linkedin']['oauth_callback_confirmed'] == 'true')) {
      // tokens retrieved
      $this->setToken($response['linkedin']);
      
      // set the response
      $return_data            = $response;
      $return_data['success'] = TRUE;        
    } else {
      // error getting the request tokens
      $this->setToken(NULL);
      
      // set the response
      $return_data = $response;
      if((array_key_exists('oauth_callback_confirmed', $response['linkedin'])) && ($response['linkedin']['oauth_callback_confirmed'] == 'true')) {
        $return_data['error'] = 'HTTP response from LinkedIn end-point was not code 200';
      } else {
        $return_data['error'] = 'OAuth callback URL was not confirmed by the LinkedIn end-point';
      }
      $return_data['success'] = FALSE;
    }
    return $return_data;
	}
633755
public function login($username, $password, $scope = 'user_info')
	{
		$response = $this->http->post($this->getUrl('oauth/token'), array(
			'grant_type'	=>	'password',
			'username'		=>	$username,
			'password'		=>	$password,
			'client_id'		=>	$this->appid,
			'client_secret'	=>	$this->appSecret,
			'scope'			=>	$scope,
		));
		$this->result = $response->json(true);
		if(!isset($this->result['error']))
		{
			return $this->accessToken = $this->result['access_token'];
		}
		else
		{
			throw new ApiException(isset($this->result['error_description']) ? $this->result['error_description'] : '', $response->httpCode());
		}
	}
1273100
public function authorize(string $action, string $scope = null): bool
    {
        if (!$this->get('authenticated')) {
            return false;
        }

        if ($this->get('state', 'enabled') !== 'enabled') {
            return false;
        }

        if (null !== $scope) {
            $action = $scope . '.' . $action;
        }

        $config = Grav::instance()['config'];
        $authorized = false;

        //Check group access level
        $groups = (array)$this->get('groups');
        foreach ($groups as $group) {
            $permission = $config->get("groups.{$group}.access.{$action}");
            $authorized = Utils::isPositive($permission);
            if ($authorized === true) {
                break;
            }
        }

        //Check user access level
        $access = $this->get('access');
        if ($access && Utils::getDotNotation($access, $action) !== null) {
            $permission = $this->get("access.{$action}");
            $authorized = Utils::isPositive($permission);
        }

        return $authorized;
    }
48851
public function getScope($scope)
    {
        if (!isset($this->allScopes[$scope])) {
            throw new ApplicationException('No definition for scope ' . $scope);
        }

        return $this->allScopes[$scope];
    }
483317
public function requestCredentialsToken()
    {
        $payload = base64_encode($this->getClientId() . ':' . $this->getClientSecret());

        $parameters = [
            'grant_type' => 'client_credentials',
        ];

        $headers = [
            'Authorization' => 'Basic ' . $payload,
        ];

        $response = $this->request->account('POST', '/api/token', $parameters, $headers);
        $response = $response['body'];

        if (isset($response->access_token)) {
            $this->accessToken = $response->access_token;
            $this->expirationTime = time() + $response->expires_in;
            $this->scope = isset($response->scope) ? $response->scope : $this->scope;

            return true;
        }

        return false;
    }
664240
public static function getSetting($scope, $key)
    {
        if (!count(self::$settings)) {
            self::load();
        }

        if (isset(self::$settings[$scope][$key])) {
            return self::$settings[$scope][$key];
        }

        return null;
    }
1221128
public function getScopeNameFrom($scope)
    {
        if (is_string($scope)) {
            $scope = $this->getScope($scope);
        }

        return $scope->nameFrom;
    }
228587
public function scopes()
	{
		if (isset($this->scopes)) {
			return $this->scopes;
		}
		
		return $this->scopes = DB::table('oauth_client_scopes')
			->select('scope_id')
			->where('client_id', $this->id)
			->lists('scope_id');
	}
319586
public function scope($scope)
	{
		$scope = (new Scope())->scope($scope);

		$this->scopes[] = $scope;
		return $scope;
	}
1053552
public function createSecretCredentialsToken(CredentialsInterface $credentials, array $scopes = array())
    {
        /** @var Command $createSession */
        $createSession = $this->createCommand()
            ->setRequest($this->client->post('encrypted/session'))
            ->setBodyEntity($credentials->toPublicArray(), 'urlencoded')
            ->setResponseClass('Maba\OAuthCommerceClient\Entity\SignedCredentials\Session')
        ;

        $registry = $this->registry;

        $httpClient = $this->client;
        return $this->createCommand()
            ->setBeforeExecute(function(Command $command) use ($createSession, $credentials, $scopes, $httpClient, $registry) {
                /** @var Session $session */
                $session = $createSession->getResult();

                $keyExchange = $registry->getKeyExchange($session->getKeyExchange()->getType());
                $encrypting = $registry->getEncrypting($session->getCipher()->getType());
                $hasher = $registry->getHasher($session->getCertificate()->getHashType());

                $serverCertificate = $httpClient->get($session->getCertificate()->getUrl())
                    ->send()
                    ->getBody(true)
                ;

                $hash = $hasher->hash($serverCertificate);
                if ($session->getCertificate()->getHash() !== $hash) {
                    throw new InvalidHashException(sprintf(
                        'Provided hash (%s) does is not as calculated from downloaded certificate (%s)',
                        $session->getCertificate()->getHash(),
                        $hash
                    ));
                }

                $additionalParameters = new Collection();
                $commonKey = $keyExchange->generateCommonKey(
                    $session->getKeyExchange()->getParameters(),
                    $serverCertificate,
                    $additionalParameters,
                    $encrypting->getKeyLength()
                );
                $encoded = http_build_query($credentials->toPrivateArray(), null, '&');
                $encrypted = $encrypting->encrypt($encoded, base64_decode($session->getCipher()->getIv()), $commonKey);

                $command->setBodyEntity(array(
                    'grant_type' => 'urn:marius-balcytis:oauth:grant-type:encrypted-credentials',
                    'scope' => implode(' ', $scopes),
                    'session_id' => $session->getSessionId(),
                    'encrypted_credentials' => $encrypted,
                ) + $additionalParameters->getAll(), 'urlencoded');
            })
            ->setRequest($this->client->post('encrypted/token'))
            ->setResponseClass('Maba\OAuthCommerceClient\Entity\AccessToken')
        ;
    }
177118
public function createAuthUrl($scope) {
    $params = array(
        'response_type=code',
        'redirect_uri=' . urlencode($this->redirectUri),
        'client_id=' . urlencode($this->clientId),
        'scope=' . urlencode($scope),
        'access_type=' . urlencode($this->accessType),
        'approval_prompt=' . urlencode($this->approvalPrompt)
    );

    if (isset($this->state)) {
      $params[] = 'state=' . urlencode($this->state);
    }
    $params = implode('&', $params);
    return self::OAUTH2_AUTH_URL . "?$params";
  }
214057
protected function getClient(Request $request)
    {
        $client = $this->apiClientRepository->findOneByKeyAndSecret($request->getUser(), $request->getPassword());
        if (!$client instanceof ApiClientInterface) {
            throw new BadClientCredentialsHttpException();
        } elseif ($client->isBlocked()) {
            throw new ClientBlockedHttpException();
        } elseif (!$client->isTrusted()) {
            throw new ClientNonTrustedHttpException();
        }

        return $client;
    }
624954
public function scopeExists($scope)
    {
        $scope = explode(' ', $scope);
        $scope_query = array();
        $count = 0;
        foreach ($scope as $key => $val) {
            $result = $this->client->query(array(
                'TableName'     => $this->config['scope_table'],
                'Select'        => 'COUNT',
                'KeyConditions' => array(
                    'scope' => array(
                        'AttributeValueList' => array(array('S' => $val)),
                        'ComparisonOperator' => 'EQ'
                    )
                )
            ));
            $count += $result['Count'];
        }

        return $count == count($scope);
    }