@param AccessTokenFactory $accessTokenFactory
@param $client_id
@param $user_id
@param $scope

@return mixed
504706
public function createAccessToken(AccessTokenFactory $accessTokenFactory, $client_id, $user_id, $scope)
    {
        return $accessTokenFactory->createAccessToken($client_id, $user_id, $scope);
    }
342971
function refreshToken($accessToken, $sessionHandle) {
		$code = $this->request ( 'GET', $this->url ( 'AccessToken', '' ), array (
				'oauth_token' => $accessToken,
				'oauth_session_handle' => $sessionHandle 
		) );
		if ($this->response ['code'] == 200) {
			
			$response = $this->extract_params ( $this->response ['response'] );
			
			return $response;
		} else {
			$this->response ['helper'] = "TokenFatal";
			return $this->response;
		}
	}
211414
public function issueToken(IAccessToken $accessToken)
    {
        $scopes = $accessToken->getScopes();

        // in case of doctrine collections, etc
        if ($scopes instanceof \Traversable) {
            $scopes = iterator_to_array($scopes);
        }

        return $this->refreshTokenStorage->generate(
            $accessToken->getUser(),
            $accessToken->getClient(),
            $scopes
        );
    }
1134984
public static function getAccessToken(
        ContextInterface $context,
        array $scopes = null,
        array $options = []
    ): AccessToken
	{
		$formParams = [
			'grant_type' => 'client_credentials',
			'client_id' => $context->getClientId(),
			'client_secret' => $context->getClientSecret(),
		];

		if ($scopes !== null) {
			$formParams['scope'] = implode(',', $scopes);
		}

        $client = SumUp::getClient($options);

		$response = $client->request(
			'POST',
			self::OAUTH_TOKEN,
			[
				'form_params' => $formParams,
			]);

		$code = $response->getStatusCode();
		if ($code !== 200) {
			$message = " Request code: $code \n Message: " . $response->getReasonPhrase();
			throw new BadRequestException($message);
		}

		$body = json_decode($response->getBody()->getContents(), true);
		$token_params = [
			$body['access_token'],
			$body['token_type'],
			$body['expires_in'],
		];

		if (isset($body['scope'])) {
			$token_params[] = $body['scope'];
		}

		return new AccessToken(...$token_params);
	}
1197556
public function createUserVHSConnection($identifier, $accessToken)
    {
        if (!$this->apiVersionIsGreaterThanV3()) {
            throw new EndpointNotSupportedByApiVersionException();
        }

        $params = [
            'identifier' => $identifier,
        ];

        return $this->put('user/vhs', $params, $accessToken);
    }
891286
public function deleteAccessToken($userId, AccessToken $accessToken)
    {
        $stmt = $this->db->prepare(
            'DELETE FROM
                access_tokens
            WHERE
                user_id = :user_id
            AND
                provider_id = :provider_id
            AND
                access_token = :access_token'
        );

        $stmt->bindValue(':user_id', $userId, PDO::PARAM_STR);
        $stmt->bindValue(':provider_id', $accessToken->getProviderId(), PDO::PARAM_STR);
        $stmt->bindValue(':access_token', $accessToken->getToken(), PDO::PARAM_STR);
        $stmt->execute();
    }
1324583
public function passValidateCredentialsAndCreateAccessTokenResponse(
        string $userName,
        string $password,
        ClientInterface $client = null,
        bool $isScopeModified = false,
        array $scope = null,
        array $extraParameters = []
    ): ResponseInterface {
        assert($client !== null);

        if (($userIdentifier = $this->getIntegration()->validateUserId($userName, $password)) === null) {
            $this->logDebug('User not found with provided username and password.', ['username' => $userName]);
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_GRANT);
        }
        assert(is_int($userIdentifier) === true);
        $this->logInfo('User authenticated with provided username and password.', ['username' => $userName]);

        $changedScopeOrNull = $this->getIntegration()->verifyAllowedUserScope($userIdentifier, $scope);
        if ($changedScopeOrNull !== null) {
            assert(is_array($changedScopeOrNull));
            $isScopeModified = true;
            $scope           = $changedScopeOrNull;
        }

        $unsavedToken = $this->getIntegration()->createTokenInstance();
        $unsavedToken
            ->setClientIdentifier($client->getIdentifier())
            ->setScopeIdentifiers($scope)
            ->setUserIdentifier($userIdentifier);
        $isScopeModified === true ? $unsavedToken->setScopeModified() : $unsavedToken->setScopeUnmodified();

        $tokenExpiresIn = $this->setUpTokenValues($unsavedToken);
        $savedToken     = $this->getIntegration()->getTokenRepository()->createToken($unsavedToken);

        $response = $this->createBodyTokenResponse($savedToken, $tokenExpiresIn);

        return $response;
    }
549571
public function getRequestAuthorization(RequestInterface $request, AccessToken $token):RequestInterface{
		$uri = $request->getUri();

		parse_str($uri->getQuery(), $query);

		$parameters = [
			'oauth_consumer_key'     => $this->options->key,
			'oauth_nonce'            => $this->nonce(),
			'oauth_signature_method' => 'HMAC-SHA1',
			'oauth_timestamp'        => (new DateTime)->format('U'),
			'oauth_token'            => $token->accessToken,
			'oauth_version'          => '1.0',
		];

		$parameters['oauth_signature'] = $this->getSignature(
			(string)$uri->withQuery('')->withFragment(''),
			array_merge($query, $parameters),
			$request->getMethod(),
			$token->accessTokenSecret
		);

		if(isset($query['oauth_session_handle'])){
			$parameters['oauth_session_handle'] = $query['oauth_session_handle'];
		}

		return $request->withHeader('Authorization', 'OAuth '.Psr7\build_http_query($parameters, true, ', ', '"'));
	}
687202
public static String generateAuthorizeUrl(String oAuthUri, String clientId, String[] scope){
        StringBuilder sb = new StringBuilder(oAuthUri);
        sb.append("/oauth/authorize?response_type=code");
        sb.append("&client_id=" + clientId);
        if (scope != null) {
            sb.append("&scope=");
            for (int i = 0; i < scope.length; i++) {
                if (i > 0) {
                    sb.append("%20");
                }
                sb.append(scope[i]);
            }
        }
        return sb.toString();
    }
786957
public static BoxAPIConnection getTransactionConnection(String accessToken, String scope) {
        return BoxTransactionalAPIConnection.getTransactionConnection(accessToken, scope, null);
    }
472553
public static function oneByScope($scope_id, $scope, $user_id = 0)
	{
		$model = self::all()
			->whereEquals('scope_id', (int)$scope_id)
			->whereEquals('scope', (string)$scope);

		if ($user_id)
		{
			$model->whereEquals('user_id', (int)$user_id);
		}

		return $model->row();
	}
211967
function userApplications (user, callback) {
  async.parallel({
    // List the trusted clients
    trusted: function (done) {
      Client.listByTrusted('true', {
        select: [
          '_id',
          'client_name',
          'client_uri',
          'application_type',
          'logo_uri',
          'trusted',
          'scopes',
          'created',
          'modified'
        ]
      }, function (err, clients) {
        if (err) { return done(err) }
        done(null, clients)
      })
    },

    // Get the authorized scope for the user
    scopes: function (done) {
      user.authorizedScope(function (err, scopes) {
        if (err) { return done(err) }
        done(null, scopes)
      })
    },

    // List of client ids the user has visited
    visited: function (done) {
      var index = 'users:' + user._id + ':clients'
      Client.__client.zrevrange(index, 0, -1, function (err, ids) {
        if (err) { return done(err) }
        done(null, ids)
      })
    }

  }, function (err, results) {
    if (err) { return callback(err) }

    // Filter out clients if the user has none of the scopes
    // defined by the client.
    var clients = results.trusted.filter(function (client) {
      if (!client.scopes || client.scopes.length === 0) {
        return true
      } else {
        return client.scopes.some(function (scope) {
          return (results.scopes.indexOf(scope) !== -1)
        })
      }
    })

    // Flag clients that have been visited
    clients.forEach(function (client) {
      client.visited = (results.visited.indexOf(client._id) !== -1)
    })

    callback(null, clients)
  })
}
853632
public function createToken($owner, $client, array $scopes = []): RefreshToken
    {
        if (empty($scopes)) {
            $scopes = $this->scopeService->getDefaultScopes();
        } else {
            $this->validateTokenScopes($scopes);
        }

        do {
            $token = RefreshToken::createNewRefreshToken(
                $this->serverOptions->getRefreshTokenTtl(),
                $owner,
                $client,
                $scopes
            );
        } while ($this->tokenRepository->tokenExists($token->getToken()));

        return $this->tokenRepository->save($token);
    }
949290
public function make($userId, $name, array $scopes = [])
    {
        $response = $this->dispatchRequestToAuthorizationServer(
            $this->createRequest($this->clients->personalAccessClient(), $userId, $scopes)
        );

        $token = tap($this->findAccessToken($response), function ($token) use ($userId, $name) {
            $this->tokens->save($token->forceFill([
                'user_id' => $userId,
                'name' => $name,
            ]));
        });

        return new PersonalAccessTokenResult(
            $response['access_token'], $token
        );
    }
376270
public function getTokenByRefreshTokenGrant(AccessToken $oldToken)
    {
        try {
            $token = $this->getAuthorizationServer()->getAccessToken('refresh_token', [
                'refresh_token' => $oldToken->getRefreshToken(),
                'scope' => $this->config[$this->grant]['scope'],
            ]);

            $this->getFrameworkBridge()->persistUserToken($token);

            return $token;
        } catch (IdentityProviderException $e) {
            $this->getFrameworkBridge()->requestUserCredentials();

            return null;
        }
    }
762719
public function getGrantedScopes($clientId, $subject)
    {
        ValidationUtility::ensureStringOrInteger('$clientId', $clientId);
        ValidationUtility::ensureString('$subject', $subject);

        $request = new GrantedScopesGetRequest();
        $request->setSubject($subject);

        return $this->callServicePostApi(
            '\Authlete\Dto\GrantedScopesGetResponse::fromJson',
            self::$GRANTED_SCOPES_GET_API_PATH . $clientId,
            null, $request);
    }
393121
private function refreshAccessToken(Provider $provider, $userId, AccessToken $accessToken)
    {
        // prepare access_token request
        $tokenRequestData = [
            'grant_type' => 'refresh_token',
            'refresh_token' => $accessToken->getRefreshToken(),
            'scope' => $accessToken->getScope(),
        ];

        $response = $this->httpClient->send(
            Request::post(
                $provider->getTokenEndpoint(),
                $tokenRequestData,
                self::getAuthorizationHeader(
                    $provider->getClientId(),
                    $provider->getSecret()
                )
            )
        );

        if (false === $response->isOkay()) {
            $responseData = $response->json();
            if (\array_key_exists('error', $responseData) && 'invalid_grant' === $responseData['error']) {
                // delete the access_token, we assume the user revoked it, that
                // is why we get "invalid_grant"
                $this->tokenStorage->deleteAccessToken($userId, $accessToken);

                return false;
            }

            throw new TokenException('unable to refresh access_token', $response);
        }

        // delete old AccessToken as we'll write a new one anyway...
        $this->tokenStorage->deleteAccessToken($userId, $accessToken);

        $accessToken = AccessToken::fromRefreshResponse(
            $provider,
            $this->dateTime,
            $response->json(),
            // provide the old AccessToken to borrow some fields if the server
            // does not provide them on "refresh"
            $accessToken
        );

        // store the refreshed AccessToken
        $this->tokenStorage->storeAccessToken($userId, $accessToken);

        return $accessToken;
    }