Create a JSON Web Token that contains a user identifier and a basic
payload including issued at, expiration and issuer.

@param mixed $userId
@param string $secret
@param int $expiration
@param string $issuer

@return string
490526
public static function create($userId, string $secret, int $expiration, string $issuer): string
    {
        $builder = self::builder();

        return $builder->setPayloadClaim('user_id', $userId)
            ->setSecret($secret)
            ->setExpiration($expiration)
            ->setIssuer($issuer)
            ->setIssuedAt(time())
            ->build()
            ->getToken();
    }
543347
public function sign(string $data, string $secret): string {
        return base64_encode(hash_hmac('md5', $data, $secret, true));
    }
1092802
private static function create_endpoints_for_microsoft($issuer) {

        $endpoints = [
            'authorization_endpoint' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
            'token_endpoint' => 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
            'userinfo_endpoint' => 'https://graph.microsoft.com/v1.0/me/',
            'userpicture_endpoint' => 'https://graph.microsoft.com/v1.0/me/photo/$value',
        ];

        foreach ($endpoints as $name => $url) {
            $record = (object) [
                'issuerid' => $issuer->get('id'),
                'name' => $name,
                'url' => $url
            ];
            $endpoint = new endpoint(0, $record);
            $endpoint->create();
        }

        // Create the field mappings.
        $mapping = [
            'givenName' => 'firstname',
            'surname' => 'lastname',
            'userPrincipalName' => 'email',
            'displayName' => 'alternatename',
            'officeLocation' => 'address',
            'mobilePhone' => 'phone1',
            'preferredLanguage' => 'lang'
        ];
        foreach ($mapping as $external => $internal) {
            $record = (object) [
                'issuerid' => $issuer->get('id'),
                'externalfield' => $external,
                'internalfield' => $internal
            ];
            $userfieldmapping = new user_field_mapping(0, $record);
            $userfieldmapping->create();
        }
        return $issuer;
    }
1212692
protected static function JsSSOString($User, $ClientID, $Secret)
    {
        if (!isset($User['client_id']))
            $User['client_id'] = $ClientID;

        $String = base64_encode(json_encode($User));
        $Timestamp = time();
        $Hash = hash_hmac('sha1', "$String $Timestamp", $Secret);

        $Result = "$String $Hash $Timestamp hmacsha1";
        return $Result;
    }
1178031
public static function validate($uuid, $secret)
    {
        $uuidData = preg_replace('/[^0-9a-f]/i', '', $uuid);

        $amountLength = substr($uuidData, 0, 1);
        $amount = substr($uuidData, 1, $amountLength);

        $serviceId = substr($uuidData, 8, 8);
        $strChecksumUUID = substr($uuidData, ($amountLength+1), (7-$amountLength));
        $hash = hash_hmac(self::HASH_METHOD, $amountLength . $amount . $serviceId, $secret);

        return substr($hash, 0, strlen($strChecksumUUID)) == $strChecksumUUID;
    }
637013
public function createIdToken($client_id, $userInfo, $nonce = null, $userClaims = null, $access_token = null)
    {
        // pull auth_time from user info if supplied
        list($user_id, $auth_time) = $this->getUserIdAndAuthTime($userInfo);

        $token = array(
            'iss'        => $this->config['issuer'],
            'sub'        => $user_id,
            'aud'        => $client_id,
            'iat'        => time(),
            'exp'        => time() + $this->config['id_lifetime'],
            'auth_time'  => $auth_time,
        );

        if ($nonce) {
            $token['nonce'] = $nonce;
        }

        if ($userClaims) {
            $token += $userClaims;
        }

        if ($access_token) {
            $token['at_hash'] = $this->createAtHash($access_token, $client_id);
        }

        return $this->encodeToken($token, $client_id);
    }
635138
public function roomToken($roomName, $userId, $perm, $expireAt)
    {
        $ver = Config::getInstance()->RTCAPI_VERSION;
        if ($ver === 'v2') {
            $params['version']="2.0";
        }
        $params['room_name'] = $roomName;
        $params['user_id'] = $userId;
        $params['perm'] = $perm;
        $params['expire_at'] = $expireAt;
        $roomAccessString = json_encode($params);
        $encodedRoomAccess = Utils::base64UrlEncode($roomAccessString);
        $sign = hash_hmac('sha1', $encodedRoomAccess, $this->_mac->_secretKey, true);
        $encodedSign = Utils::base64UrlEncode($sign);
        return $this->_mac->_accessKey . ":" . $encodedSign . ":" . $encodedRoomAccess;
    }
813767
protected function createToken($userId, $csrfToken, Carbon $expiration)
    {
        return JWT::encode([
            'sub' => $userId,
            'csrf' => $csrfToken,
            'expiry' => $expiration->getTimestamp(),
        ], $this->encrypter->getKey());
    }
420202
private static function create_endpoints_for_google($issuer) {

        $record = (object) [
            'issuerid' => $issuer->get('id'),
            'name' => 'discovery_endpoint',
            'url' => 'https://accounts.google.com/.well-known/openid-configuration'
        ];
        $endpoint = new endpoint(0, $record);
        $endpoint->create();
        return $issuer;
    }
1278807
public static function generateAssertion(string $secret, string $oauthClientId, string $baseUrl, string $user): string
    {
        $data = [
            'iss' => 'urn:atlassian:connect:clientid:'.$oauthClientId,
            'sub' => 'urn:atlassian:connect:userkey:'.$user,
            'iat' => \time(),
            'exp' => \strtotime('+1 minutes'),
            'tnt' => $baseUrl,
            'aud' => 'https://auth.atlassian.io',
        ];

        return JWT::encode($data, $secret);
    }
1255228
public static function parser(string $token, string $secret): Parse
    {
        $jwt = new Jwt($token, $secret);

        return new Parse($jwt, new Validate(), new Encode());
    }
734183
public function getUserToken($userId, $ip, $userAgent = null)
    {
        $query = $this->getUserTokenQuery($userId, $ip, $userAgent);

        return $this->findOneWith($query);
    }
153261
public function isValid($payload, $secret, $signature)
    {
        return $signature === hash_hmac($this->hashAlgorithm, $payload, $secret, true);
    }
999844
public static function sign($msg, $secret)
    {
        $signature = hash_hmac("sha1", $msg, $secret, true);
        return strtr(
            base64_encode($signature),
            '/+', '_-'
        );
    }
1256608
protected function _getQRCodeUrl($title, $name, $secret)
    {
        if (empty($title)) {
            return 'otpauth://totp/'.rawurlencode($name).'?secret='.$secret;
        } else {
            return 'otpauth://totp/'.rawurlencode($title).':'.rawurlencode($name).'?secret='.$secret.'&issuer='.rawurlencode($title);
        }        
    }
416204
public function newToken(AuthenticatableContract $user)
    {
      $this->decoded = null;

      $tokenId = md5(uniqid($user->email, true));
      $issuedAt   = time();
      $notBefore  = $issuedAt + $this->notBefore_delay;
      $expire     = $notBefore + $this->expire_after;
      $jwt_key = $this->key;
      $issuer = $this->issuer;
      $subject = $user->{$this->id_field};

      $data = [];
      foreach ($this->includes as $k) $data[$k] = $user->{$k};

      $token = [
          "iss" => $this->issuer,
          "jti" => $tokenId,
          "iat" => $issuedAt,
          "nbf" => $notBefore,
          "exp" => $expire,
          "data" => $data,
          "sub" => $subject
        ];

      return $this->token = JWT::encode($token, $jwt_key, 'HS512');
    }
931408
public static function getPayload(string $token, string $secret): array
    {
        $parser = self::parser($token, $secret);

        return $parser->validate()->parse()->getPayload();
    }