Create the ID token.

@param array   $scopes         Array of scopes to include.
@param integer $lifetime       Lifetime of the token, in seconds.
@param boolean $secret_encoded True to base64 decode the client secret.

@return string
548320
public function generate(array $scopes, $lifetime = self::DEFAULT_LIFETIME, $secret_encoded = true)
    {
        $time           = time();
        $payload        = [
            'iat' => $time,
            'scopes' => $scopes,
            'exp' => $time + $lifetime,
            'aud' => $this->audience,
        ];
        $payload['jti'] = md5(json_encode($payload));

        $secret = $secret_encoded ? base64_decode(strtr($this->secret, '-_', '+/')) : $this->secret;

        return JWT::encode($payload, $secret);
    }
630054
public function getCode($secret, $timeSlice = null)
    {
        if ($timeSlice === null) {
            $timeSlice = floor(time() / 30);
        }

        $secretkey = $this->_base32Decode($secret);

        // Pack time into binary string
        $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
        // Hash it with users secret key
        $hm = hash_hmac('SHA1', $time, $secretkey, true);
        // Use last nipple of result as index/offset
        $offset = ord(substr($hm, -1)) & 0x0F;
        // grab 4 bytes of the result
        $hashpart = substr($hm, $offset, 4);

        // Unpak binary value
        $value = unpack('N', $hashpart);
        $value = $value[1];
        // Only 32 bits
        $value = $value & 0x7FFFFFFF;

        $modulo = pow(10, $this->_codeLength);
        return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
    }
755864
public function getTwitterTokened($token,$secret)
    {
        return new TwitterOAuth($this->consumer_key, $this->consumer_secret, $token,$secret);
    }
532774
protected static function createNew(
        int $ttl,
        TokenOwnerInterface $owner = null,
        Client $client = null,
        array $scopes = null
    ): self {
        if (is_array($scopes)) {
            $scopes = array_map(function ($scope) {
                return (string) $scope;
            }, $scopes);
        }

        $token = new static();

        $token->token = bin2hex(random_bytes(20));
        $token->owner = $owner;
        $token->client = $client;
        $token->scopes = $scopes ?? [];
        $token->expiresAt = $ttl ? (new DateTime('@' . time(), new DateTimeZone('UTC')))->modify("+$ttl seconds") : null;

        return $token;
    }
505698
public function userFromTokenAndSecret($token, $secret)
    {
        $tokenCredentials = new TokenCredentials();

        $tokenCredentials->setIdentifier($token);
        $tokenCredentials->setSecret($secret);

        $user = $this->server->getUserDetails(
            $tokenCredentials, $this->shouldBypassCache($token, $secret)
        );

        $instance = (new User)->setRaw($user->extra)
            ->setToken($tokenCredentials->getIdentifier(), $tokenCredentials->getSecret());

        return $instance->map([
            'id' => $user->uid,
            'nickname' => $user->nickname,
            'name' => $user->name,
            'email' => $user->email,
            'avatar' => $user->imageUrl,
        ]);
    }
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
        );
    }
1184943
protected function generateSig($endpoint, array $params, $secret)
    {
        $sig = $endpoint;
        ksort($params);
        foreach ($params as $key => $val) {
            $sig .= "|$key=$val";
        }
        return hash_hmac('sha256', $sig, $secret, false);
    }
825035
public function setToken(string $token, int $lifetime = 7200): AccessTokenInterface
    {
        $this->getCache()->set($this->getCacheKey(), [
            $this->tokenKey => $token,
            'expires_in' => $lifetime,
        ], $lifetime - $this->safeSeconds);

        if (!$this->getCache()->has($this->getCacheKey())) {
            throw new RuntimeException('Failed to cache access token.');
        }

        return $this;
    }
374775
public function create($name, $id, $secret)
    {
        return $this->getConnection()->table('oauth_clients')->insertGetId([
            'id' => $id,
            'name' => $name,
            'secret' => $secret,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);
    }
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);
    }
515847
public static function generateImageTokenSecretSignature($host, $uri, $token, $secret)
    {
        $host = strtolower($host);

        $base = [];

        $magicsLength = sizeof(self::$imageUrlTokenMagics);
        $additional = [$host, $uri, $secret, $token];
        $offset = 0;
        foreach (str_split($token) as $number) {
            $offset += ord($number);
            $magic = self::$imageUrlTokenMagics[$offset % $magicsLength];
            $base[] = $magic;
            $base[] = array_pop($additional);
            $offset += ord($magic[0]);
            $base[] = sha1($offset, true);
            if (!$additional) {
                break;
            }
        }
        $base = join(chr($offset & 0xff), $base);
        $sha1 = str_split(sha1($base, true));
        $base = [];
        for ($i = 0; $i < 24; $i++) {
            $base[] = $sha1[($i + $offset)%sizeof($sha1)];
        }
        $base = join('', $base);
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($base));
    }
1182243
private function generateCredentialsFile($api, $scopes) {

        $credentialsPath = Yii::getAlias($this->configPath) . '/' . $api . '_' . $this->getUuid() . '.json';

        $client = new Google_Client();
        $client->setAuthConfigFile($this->clientSecretPath);
        $client->setAccessType('offline');
        $client->setScopes(implode(' ', $scopes));

        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        $this->stdout(sprintf("Open the following link in your browser:\n  %s\n", $authUrl));

        $authenticated = false;

        while (!$authenticated) {
            $authCode = $this->prompt("Enter the verification code: ");

            // Exchange authorization code for an access token.
            try {
                $accessToken = $client->authenticate($authCode);
                $authenticated = true;
            } catch (Google_Auth_Exception $e) {
                $this->stderr($e->getMessage() . "\n");
            }
        }

        // Store the credentials to disk.
        if (!is_dir(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        /** @var string $accessToken */
        file_put_contents($credentialsPath, $accessToken);

        return $credentialsPath;

    }
829437
private function getResponse(string $secret, string $challenge): string
    {
        if (\strlen($secret) > 64) {
            $secret = pack('H32', md5($secret));
        }

        if (\strlen($secret) < 64) {
            $secret = str_pad($secret, 64, \chr(0));
        }

        $kipad = substr($secret, 0, 64) ^ str_repeat(\chr(0x36), 64);
        $kopad = substr($secret, 0, 64) ^ str_repeat(\chr(0x5C), 64);

        $inner = pack('H32', md5($kipad.$challenge));
        $digest = md5($kopad.$inner);

        return $digest;
    }
238780
private function getAccessToken(Provider $provider, $userId, $scope)
    {
        $accessTokenList = $this->tokenStorage->getAccessTokenList($userId);
        foreach ($accessTokenList as $accessToken) {
            if ($provider->getProviderId() !== $accessToken->getProviderId()) {
                continue;
            }
            if ($scope !== $accessToken->getScope()) {
                continue;
            }

            return $accessToken;
        }

        return false;
    }
172119
private function encode($lifetime, $customPayload = null)
    {
        $time    = time();
        $payload = ['iat' => $time];

        if (null !== $customPayload) {
            $payload = array_merge($customPayload, $payload);
        }

        $jti = md5(json_encode($payload));

        $payload['jti'] = $jti;

        if (null !== $this->localId) {
            $payload['aud'] = $this->localId;
        }

        if (null !== $lifetime) {
            $payload['exp'] = ($time + $lifetime);
        }

        $jwt = \JWT::encode($payload, $this->secret);

        return $jwt;
    }
780477
private static function getAuthToken(string $oauthClientId, string $secret, string $baseUrl, string $username): string
    {
        $result = (new Client())->post('https://auth.atlassian.io/oauth2/token', [
            'form_params' => [
                'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                'assertion' => JWTGenerator::generateAssertion($secret, $oauthClientId, $baseUrl, $username),
            ],
        ]);

        return \json_decode($result->getBody()->getContents(), true)['access_token'];
    }
836368
function (auth) {
      var clientCredentials = Buffer.from(auth.slice('basic '.length), 'base64').toString().split(':')
      var clientId = querystring.unescape(clientCredentials[0])
      var clientSecret = querystring.unescape(clientCredentials[1])
      return { id: clientId, secret: clientSecret }
    }