Create a new token (and generate the token)

@param TokenOwnerInterface $owner
@param Client              $client
@param string[]|Scope[]    $scopes
@return AccessToken
@throws OAuth2Exception
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);
    }
1321012
protected function refreshToken(TokenInterface $expiredToken, ResourceOwnerInterface $resourceOwner)
    {
        if (!$expiredToken->getRefreshToken()) {
            return $expiredToken;
        }

        $token = new OAuthToken($resourceOwner->refreshAccessToken($expiredToken->getRefreshToken()));
        $token->setRefreshToken($expiredToken->getRefreshToken());
        $this->tokenStorage->setToken($token);

        return $token;
    }
1354673
public function newAuthorizeRequest($owner, $owner_id, $options)
  {
    return $this->authServer->getGrantType('authorization_code')->newAuthoriseRequest($owner, $owner_id, $options);
  }
706627
protected function prepareTokenResponse(
        AccessToken $accessToken,
        RefreshToken $refreshToken = null,
        bool $useRefreshTokenScopes = false
    ): ResponseInterface {
        $owner = $accessToken->getOwner();
        $scopes = $useRefreshTokenScopes ? $refreshToken->getScopes() : $accessToken->getScopes();

        $responseBody = [
            'access_token' => $accessToken->getToken(),
            'token_type' => 'Bearer',
            'expires_in' => $accessToken->getExpiresIn(),
            'scope' => implode(' ', $scopes),
            'owner_id' => $owner ? $owner->getTokenOwnerId() : null,
        ];

        if (null !== $refreshToken) {
            $responseBody['refresh_token'] = $refreshToken->getToken();
        }

        return new Response\JsonResponse(array_filter($responseBody));
    }
852582
public function refreshAccessToken(AccessToken $token = null):AccessToken{

		if($token === null){
			$token = $this->storage->getAccessToken($this->serviceName);
		}

		$refreshToken = $token->refreshToken;

		if(empty($refreshToken)){

			if(!$this instanceof AccessTokenForRefresh){
				throw new ProviderException(sprintf('no refresh token available, token expired [%s]', date('Y-m-d h:i:s A', $token->expires)));
			}

			$refreshToken = $token->accessToken;
		}

		$body = [
			'client_id'     => $this->options->key,
			'client_secret' => $this->options->secret,
			'grant_type'    => 'refresh_token',
			'refresh_token' => $refreshToken,
			'type'          => 'web_server',
		];

		$request = $this->requestFactory
			->createRequest('POST', $this->refreshTokenURL ?? $this->accessTokenURL)
			->withHeader('Content-Type', 'application/x-www-form-urlencoded')
			->withHeader('Accept-Encoding', 'identity')
			->withBody($this->streamFactory->createStream(http_build_query($body, '', '&', PHP_QUERY_RFC1738)))
		;

		foreach($this->authHeaders as $header => $value){
			$request = $request->withAddedHeader($header, $value);
		}

		$newToken = $this->parseTokenResponse($this->http->sendRequest($request));

		if(empty($newToken->refreshToken)){
			$newToken->refreshToken = $refreshToken;
		}

		$this->storage->storeAccessToken($this->serviceName, $newToken);

		return $newToken;
	}
84014
public function setAuth($client_token, $client_secret, $access_token)
    {
        $this->authentication->setAuth($client_token, $client_secret, $access_token);

        return $this;
    }
721471
def token_new():
    """"""
    form = TokenForm(request.form)
    form.scopes.choices = current_oauth2server.scope_choices()

    if form.validate_on_submit():
        t = Token.create_personal(
            form.data['name'], current_user.get_id(), scopes=form.scopes.data
        )
        db.session.commit()
        session['show_personal_access_token'] = True
        return redirect(url_for(".token_view", token_id=t.id))

    if len(current_oauth2server.scope_choices()) == 0:
        del(form.scopes)

    return render_template(
        "invenio_oauth2server/settings/token_new.html",
        form=form,
    )
345418
public function createWithExpirationDate(ApiClientInterface $client, UserInterface $user = null)
    {
        $accessToken = $this->create($client, $user);
        $accessToken->setExpiredAt(new \DateTime($this->tokenExpiration));

        return $accessToken;
    }
157142
protected function createResourceOwner(array $response, AccessToken $token)
  {
    $result = isset($response['result']) ? $response['result'] : [];

    /**
     * @var $result AuthUserDetailsResponse
     */
    if(!($result instanceof AuthUserDetailsResponse))
    {
      $result = AuthUserDetailsResponse::make($result);
    }
    $user = new OAuthUser(
      [
        'uid'         => $result->userFid,
        'nickname'    => ValueAs::nonempty(
          $result->displayName,
          $result->firstName,
          $result->lastName,
          $result->username,
          $result->userFid
        ),
        'locale'      => $result->language,
        'location'    => $result->timezone,
        'name'        => $result->displayName,
        'imageUrl'    => $result->avatarUrl,
        'firstName'   => $result->firstName,
        'lastName'    => $result->lastName,
        'description' => $result->description,
        'email'       => $result->username,
      ], $result->userFid
    );
    $user->setAuthUserDetails($result);
    return $user;
  }
1197815
public function persistClientToken($clientId, $accessToken, $expiration, $role)
    {
        /** @var \Illuminate\Database\Query\Builder $table */
        $table = app('db')->connection()->table('clients');

        // If the record doesn't already exist, add it.
        if (! $table->where(['client_id' => $clientId])->exists()) {
            $table->insert(['client_id' => $clientId]);
        }

        // Update record with the new access token & expiration.
        $table->where(['client_id' => $clientId])->update([
            'access_token' => $accessToken,
            'access_token_expiration' => $expiration,
        ]);
    }
479775
protected function clientIssueToken(array $parameters, ClientInterface $determinedClient): ResponseInterface
    {
        if ($determinedClient->isClientGrantEnabled() === false) {
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_UNAUTHORIZED_CLIENT);
        }

        $scope = $this->clientGetScope($parameters);
        list ($isScopeValid, $scopeList, $isScopeModified) =
            $this->clientGetIntegration()->clientValidateScope($determinedClient, $scope);
        if ($isScopeValid === false) {
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_SCOPE);
        }

        $response = $this->clientGetIntegration()->clientCreateAccessTokenResponse(
            $determinedClient,
            $isScopeModified,
            $scopeList,
            $parameters
        );

        return $response;
    }
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);
    }
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));
    }
874245
public function grant(IRequest $request)
    {
        $client = $this->clientAuthenticator->authenticate($request);

        if (!$client->isAllowedToUse($this)) {
            throw new UnauthorizedClientException('Client can not use this grant type.');
        }

        if (!$client->getSecret()) {
            throw new InvalidClientException('Only confidential clients can use this method.');
        }

        $requestedScopes = $request->request('scope');
        $availableScopes = $client->getScopes();

        if (empty($availableScopes)) {
            $availableScopes = $this->scopeResolver->getDefaultScopes();
        }

        if (empty($availableScopes)) {
            throw new InvalidScopeException('Scope parameter has to be specified.');
        }

        $scopes = $this->scopeResolver->intersect($requestedScopes, $availableScopes);

        return $this->accessTokenStorage->generate(
            $client->getOwner(),
            $client,
            $scopes
        );
    }
621958
public function associateScope(AuthCodeEntity $token, ScopeEntity $scope)
    {
        $this->getConnection()->table('oauth_auth_code_scopes')->insert([
            'auth_code_id' => $token->getId(),
            'scope_id' => $scope->getId(),
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);
    }
1213157
public function createToken($redirectUri, $owner, $client, array $scopes = []): AuthorizationCode
    {
        if (empty($scopes)) {
            $scopes = $this->scopeService->getDefaultScopes();
        } else {
            $this->validateTokenScopes($scopes);
        }

        do {
            $token = AuthorizationCode::createNewAuthorizationCode(
                $this->serverOptions->getAuthorizationCodeTtl(),
                $redirectUri,
                $owner,
                $client,
                $scopes
            );
        } while ($this->tokenRepository->tokenExists($token->getToken()));

        return $this->tokenRepository->save($token);
    }
604185
public static function generateToken($client_id, $redirect_uri, $scope = 'public_content')
  {
    $params = array(
      'client_id'     => $client_id,
      'redirect_uri'  => $redirect_uri,
      'response_type' => 'token',
      'scope'         => $scope
    );
    header('location:https://www.instagram.com/oauth/authorize/?' . http_build_query($params));
    die;
  }