Authorization::createPayload

@param \O2System\Security\Authentication\Oauth\Client\Account $client
@param array                                                  $scope

@return array
@throws \Exception
355895
protected function createPayload(Oauth\Client\Account $client, array $scope = [])
    {
        // token to encrypt
        $expires = time() + $this->config[ 'token' ][ 'lifetime' ];

        $id = Token::generate(40, Token::ALPHAHASH_STRING);
        $payload = [
            'id'         => $id,
            // the internal id of the token
            'jti'        => $id,
            // a unique token identifier for the token (JWT ID)
            'iss'        => $this->config[ 'issuer' ],
            // the id of the server who issued the token (Issuer)
            'aud'        => $client->id,
            // the id of the client who requested the token (Audience)
            'sub'        => ($this->user->offsetExists('id') ? $this->user->offsetGet('id') : null),
            // the id of the user for which the token was released (Subject)
            'exp'        => $expires,
            'iat'        => time(),
            'token_type' => $this->config[ 'token' ][ 'type' ],
            'scope'      => empty($scope) ? null : implode(' ', $scope),
        ];

        if ($client->offsetExists('metadata')) {
            if (is_array($client->metadata)) {
                $payload = array_merge($client->metadata, $payload);
            }
        }

        return $payload;
    }
763336
public static function create(int $oauthClientId, string $url, array $customHeaders = []): BunqResponseInt
    {
        $apiClient = new ApiClient(static::getApiContext());
        $responseRaw = $apiClient->post(
            vsprintf(
                self::ENDPOINT_URL_CREATE,
                [static::determineUserId(), $oauthClientId]
            ),
            [self::FIELD_URL => $url],
            $customHeaders
        );

        return BunqResponseInt::castFromBunqResponse(
            static::processForId($responseRaw)
        );
    }
1181001
public function createAskResourceOwnerForApprovalResponse(
        string $type,
        ClientInterface $client,
        string $redirectUri = null,
        bool $isScopeModified = false,
        array $scopeList = null,
        string $state = null,
        array $extraParameters = []
    ): ResponseInterface {
        /** @var Client $client */
        assert($client instanceof Client);

        // TODO think if we can receive objects instead of individual properties
        $scopeList = empty($scopeList) === true ? null : implode(' ', $scopeList);
        $filtered  = array_filter([
            self::SCOPE_APPROVAL_TYPE              => $type,
            self::SCOPE_APPROVAL_CLIENT_ID         => $client->getIdentifier(),
            self::SCOPE_APPROVAL_CLIENT_NAME       => $client->getName(),
            self::SCOPE_APPROVAL_REDIRECT_URI      => $redirectUri,
            self::SCOPE_APPROVAL_IS_SCOPE_MODIFIED => $isScopeModified,
            self::SCOPE_APPROVAL_SCOPE             => $scopeList,
            self::SCOPE_APPROVAL_STATE             => $state,
        ], function ($value) {
            return $value !== null;
        });

        return new RedirectResponse($this->createRedirectUri($this->getApprovalUriString(), $filtered));
    }
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;
    }
75473
public function refreshCreateAccessTokenResponse(
        ClientInterface $client,
        \Limoncello\OAuthServer\Contracts\TokenInterface $token,
        bool $isScopeModified,
        array $scope = null,
        array $extraParameters = []
    ): ResponseInterface {
        $this->logDebug('Prepare refresh token.');

        /** @var TokenInterface $token */
        assert($token instanceof TokenInterface);

        $updatedToken   = clone $token;
        $tokenExpiresIn = $this->getIntegration()->isRenewRefreshValue() === false ?
            $this->setUpTokenValue($updatedToken) : $this->setUpTokenValues($updatedToken);

        $tokenRepo = $this->getIntegration()->getTokenRepository();
        if ($isScopeModified === false) {
            $tokenRepo->updateValues($updatedToken);
        } else {
            assert(is_array($scope));
            $tokenRepo->inTransaction(function () use ($tokenRepo, $updatedToken, $scope) {
                $tokenRepo->updateValues($updatedToken);
                $tokenRepo->unbindScopes($updatedToken->getIdentifier());
                $tokenRepo->bindScopeIdentifiers($updatedToken->getIdentifier(), $scope);
            });
            $updatedToken->setScopeModified()->setScopeIdentifiers($scope);
        }
        $response = $this->createBodyTokenResponse($updatedToken, $tokenExpiresIn);

        return $response;
    }
250745
@Beta
  public GoogleCredential createScoped(Collection<String> scopes) {
    if (serviceAccountPrivateKey == null) {
      return this;
    }
    return toBuilder()
        .setServiceAccountScopes(scopes)
        .build();
  }
1078054
public function updateClientAuthorization($clientId, ClientAuthorizationUpdateRequest $request)
    {
        ValidationUtility::ensureStringOrInteger('$clientId', $clientId);

        return $this->callServicePostApi(
            '\Authlete\Dto\ApiResponse::fromJson',
            self::$CLIENT_AUTHORIZATION_UPDATE_API_PATH . $clientId,
            null, $request);
    }
981580
protected function createAuthCodeClient(ClientRepository $clients)
    {
        $userId = $this->option('user_id') ?: $this->ask(
            'Which user ID should the client be assigned to?'
        );

        $name = $this->option('name') ?: $this->ask(
            'What should we name the client?'
        );

        $redirect = $this->option('redirect_uri') ?: $this->ask(
            'Where should we redirect the request after authorization?',
            url('/auth/callback')
        );

        $client = $clients->create(
            $userId, $name, $redirect
        );

        $this->info('New client created successfully.');

        $this->outputClientDetails($client);
    }
297960
public function createToken($name, array $scopes = [])
    {
        return Container::getInstance()->make(PersonalAccessTokenFactory::class)->make(
            $this->getKey(), $name, $scopes
        );
    }
1135831
protected function createResourceFromClient(ClientEntity $client)
    {
        $resource = new Resource(
            $this->generateReadUrl($client->getId()),
            array(
                 'id'           => $client->getId(),
                 'publicId'     => $client->getPublicId(),
                 'secret'       => $client->getSecret(),
                 'redirectUris' => $client->getRedirectUris(),
                 'grants'       => $client->getAllowedGrantTypes(),
            )
        );

        return $resource;
    }
701154
public function scopeExists($scope, $client_id = null)
    {
        $scopes = explode(' ', $scope);
        if ($client_id) {
            // Get Client
            $client = $this->em->getRepository('OAuth2ServerBundle:Client')->find($client_id);

            if (!$client) {
                return false;
            }

            $valid_scopes = $client->getScopes();

            foreach ($scopes as $scope) {
                if (!in_array($scope, $valid_scopes)) {
                    return false;
                }
            }

            return true;
        }

        $valid_scopes = $this->sm->findScopesByScopes($scopes);

        return count($valid_scopes) == count($scopes);
    }
1195322
public static function make($account = null, $clientId = null, $clientSecret = null)
    {
        return new static($account, $clientId, $clientSecret);
    }
690986
public static function create(array $body, $collectionUrl, ClientInterface $client)
    {
        $result = parent::create($body, $collectionUrl, $client);

        return new Subscription($result->getData(), $collectionUrl, $client);
    }
120982
public function beginSession($callback, array $scope = [])
    {
        $requestUrl = $this->config['request_url'];

        if (0 < count($scope)) {
            $requestUrl .= ((false === strpos($requestUrl, '?')) ? '?' : '&') . 'scope=' . rawurlencode(implode(' ', $scope));
        }

        $response = $this->sendCustomOauthPostRequest(
            $requestUrl,
            [
                'callback' => $callback,
                'token' => null,
                'token_secret' => null,
            ]
        );

        parse_str($response->getBody(), $responseData);

        if (!isset($responseData['oauth_callback_confirmed'])) {
            throw new UnexpectedValueException('Oauth exchange is missing `oauth_callback_confirmed`.');
        } elseif (!isset($responseData['oauth_token'])) {
            throw new UnexpectedValueException('Oauth exchange is missing `oauth_token`.');
        } elseif (!isset($responseData['oauth_token_secret'])) {
            throw new UnexpectedValueException('Oauth exchange is missing `oauth_token_secret`.');
        }

        if ('true' !== $responseData['oauth_callback_confirmed']) {
            throw new UnexpectedValueException('Oauth exchange must have `oauth_callback_confirmed` as `true`.');
        }

        $this->authentication->getTokenStorage()->setRequestToken($responseData['oauth_token']);
        $this->authentication->getTokenStorage()->setRequestTokenSecret($responseData['oauth_token_secret']);

        $redirect = $this->config['authorize_url'];
        $redirect .= ((false === strpos($redirect, '?')) ? '?' : '&') . 'oauth_token=' . rawurlencode($this->authentication->getTokenStorage()->getRequestToken());

        return $redirect;
    }
760649
public function createToken($owner, $client, array $scopes = []): AccessToken
    {
        if (empty($scopes)) {
            $scopes = $this->scopeService->getDefaultScopes();
        } else {
            $this->validateTokenScopes($scopes);
        }

        do {
            $token = AccessToken::createNewAccessToken(
                $this->serverOptions->getAccessTokenTtl(),
                $owner,
                $client,
                $scopes
            );
        } while ($this->tokenRepository->tokenExists($token->getToken()));

        return $this->tokenRepository->save($token);
    }
405741
public function newAction(Request $request)
    {
        $acl = $this->get('bacon_acl.service.authorization');

        if (!$acl->authorize('module', 'NEW')) {
            throw $this->createAccessDeniedException();
        }

        $breadcumbs = $this->container->get('bacon_breadcrumbs');

        $breadcumbs->addItem([
            'title' => 'Module',
            'route' => 'module',
        ]);

        $breadcumbs->addItem([
            'title' => 'New',
            'route' => '',
        ]);

        $form = $this->createForm(ModuleFormType::class, new Module());

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            $handler = new ModuleFormHandler(
                $form,
                $this->getDoctrine()->getManager(),
                $this->get('session')->getFlashBag()
            );

            if ($handler->save()) {
                return $this->redirect($this->generateUrl('module'));
            }
        }

        return [
            'form'   => $form->createView(),
        ];
    }
122701
public function checkAuthorization($authorization, $client_id, $access_token) {
        $instance = new checkAuthorization($this, $this->getUserAgent(), $authorization, $client_id, $access_token);
        return $instance;
    }