Decode and parse a token to make sure it is valid

@param string $token The encrypted token

@return string The plaintext token (or false on failure)
15586
public static function decodeToken($token) {
        global $CFG;
        $plain = AesCtr::decrypt($token, $CFG->websocket_secret, 256) ;
        $pieces = explode('::', $plain);
        if ( count($pieces) != 4 ) return false;
        return $plain;
    }
564270
protected function composeSignatureKey($token = null)
    {
        $signatureKeyParts = [
            $this->consumerSecret
        ];

        if ($token === null) {
            $token = $this->getAccessToken();
        }
        if (is_object($token)) {
            $signatureKeyParts[] = $token->getTokenSecret();
        } else {
            $signatureKeyParts[] = '';
        }

        $signatureKeyParts = array_map('rawurlencode', $signatureKeyParts);

        return implode('&', $signatureKeyParts);
    }
400585
public static function validate($token)
    {
        if ($token === null) {
            return false;
        }

        if (gettype($token) == 'string' && trim($token) == '') {
            // False if String Empty
            return false;
        }

        if (strlen($token) < 20) return false;
        if (strlen($token) > 50) return false;

        // Type 0: c0afcccdde5081d6429de37d16166ead
        $type0RegExpression = '/(^[a-z0-9]+$)/i';

        // Type 1: de305d54-75b4-431b-adb2-eb6b9e546014
        // UUID strict: http://en.wikipedia.org/wiki/Universally_unique_identifier#Definition
        $type1RegExpression = '/(^[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}$)/i';

        if (preg_match($type0RegExpression, $token) == false
            && preg_match($type1RegExpression, $token) == false
        ) {
            return false;
        }

        return true;
    }
343418
public function decode($token)
    {
        $jwt = new JWT();

        try {
            $decoded = Codec::decode($token, $this->secret, ['HS256']);
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            $jwt->setSignatureValid(false);
        } catch (\Exception $e) {
        }

        list($header, $payload, $signature) = explode(".", $token);
        $header    = base64_decode($header);
        $payload   = json_decode(base64_decode($payload));
        $signature = base64_decode($signature);

        // Retrieves start and end public claims other claims are going to be ignored
        $jwt->setStart(new \DateTime('@'.$payload->nbf));
        $jwt->setEnd(new \Datetime('@'.$payload->exp));

        // Retrieves private claims
        foreach ($payload->data as $key => $value) {
            $jwt->set($key, $value);
        }

        return $jwt;
    }
1075589
protected function validateToken($token)
  {
    $hash   = explode(':', config('app.key'))[0];
    $secret = explode(':', config('app.key'))[1];

    if ($hash == 'base64') $secret = base64_decode($secret);

    $validator = new TokenValidator;

    $validator->splitToken($token)
        ->validateExpiration()
        ->validateSignature($secret);

    $payLoad = $validator->getPayload();

    return json_decode($payLoad, true);
  }
875581
public function isValid($token)
    {
        try {
            $publicKey = openssl_pkey_get_public(file_get_contents($this->projectDir . '/var/jwt/public.pem'));

            $jws = SimpleJWS::load($token);

            return $jws->verify($publicKey, self::ALG) && $this->isTokenNotExpired($token);
        } catch (\InvalidArgumentException $ex) {
            return false;
        }
    }
496887
public function decodeToken($token)
    {
        try {
            $parser = new Parser();

            if (!$token = $parser->parse((string) $token)) {
                throw new Exception('Token inválido');
            }

            return $token;
        } catch (Exception $e) {
            abort(401, 'Favor efetuar o login novamente');
        }
    }
40725
public function fromString($token)
    {
        $segments = explode('.', $token);

        if (count($segments) == 3)
        {
            list($header, $payload, $signature) = $segments;

            $this->_header    = $this->_fromJson($this->_fromBase64url($header));
            $this->_claims    = $this->_fromJson($this->_fromBase64url($payload));
            $this->_signature = $this->_fromBase64url($signature);

            if(isset($this->_header['alg'])) {
                $this->setAlgorithm($this->_header['alg']);
            } else {
                $this->setAlgorithm('none');
            }
        }
        else throw new InvalidArgumentException(sprintf('The token "%s" is an invalid JWT', $token));

        return $this;
    }
1306292
private static function classify_token( $token ) {
		$param = array();

		list( $param['optional'], $token )  = self::is_optional( $token );
		list( $param['repeating'], $token ) = self::is_repeating( $token );

		$p_name  = '([a-z-_0-9]+)';
		$p_value = '([a-zA-Z-_|,0-9]+)';

		if ( '--<field>=<value>' === $token ) {
			$param['type'] = 'generic';
		} elseif ( preg_match( "/^<($p_value)>$/", $token, $matches ) ) {
			$param['type'] = 'positional';
			$param['name'] = $matches[1];
		} elseif ( preg_match( "/^--(?:\\[no-\\])?$p_name/", $token, $matches ) ) {
			$param['name'] = $matches[1];

			$value = substr( $token, strlen( $matches[0] ) );

			// substr returns false <= PHP 5.6, and '' PHP 7+
			if ( false === $value || '' === $value ) {
				$param['type'] = 'flag';
			} else {
				$param['type'] = 'assoc';

				list( $param['value']['optional'], $value ) = self::is_optional( $value );

				if ( preg_match( "/^=<$p_value>$/", $value, $matches ) ) {
					$param['value']['name'] = $matches[1];
				} else {
					$param = array(
						'type' => 'unknown',
					);
				}
			}
		} else {
			$param['type'] = 'unknown';
		}

		return $param;
	}
385343
public function check($token)
    {
        if (! Cache::has($this->getCacheKey()))
            return false;

        return Cache::get($this->getCacheKey()) === $token;
    }
265225
public function getToken(string $token)
    {
        /* @var \ZfrOAuth2\Server\Model\AbstractToken $tokenFromDb */
        $tokenFromDb = $this->tokenRepository->findByToken($token);

        // Because the collation is most often case insensitive, we need to add a check here to ensure
        // that the token matches case
        if (! $tokenFromDb || ! hash_equals($tokenFromDb->getToken(), $token)) {
            return null;
        }

        return $tokenFromDb;
    }
985261
public function decode($token)
    {
        if (\substr_count($token, '.') < 2) {
            throw new JWTException('Invalid token: Incomplete segments', static::ERROR_TOKEN_INVALID);
        }

        $token = \explode('.', $token, 3);
        $this->validateHeader((array) $this->urlSafeDecode($token[0]));

        // Validate signature.
        if (!$this->verify($token[0] . '.' . $token[1], $token[2])) {
            throw new JWTException('Invalid token: Signature failed', static::ERROR_SIGNATURE_FAILED);
        }

        $payload = (array) $this->urlSafeDecode($token[1]);

        $this->validateTimestamps($payload);

        return $payload;
    }
1368450
protected function _setToken($token)
    {
        //Prevents an empty value is serialized
        if (!$token) {
            return $token;
        }
        $token = is_string($token) ? $token : serialize($token);

        return substr(Security::hash($token, 'sha1', Configure::read('Tokens.tokenSalt')), 0, 25);
    }
163607
private function verify(string $token): array
    {
        $jsonConverter = new StandardConverter();
        $serializer = new JWSCompactSerializer($jsonConverter);
        $jws = $serializer->unserialize($token);
        $this->signatureHeaderCheckerManager->check($jws, 0);
        if (false === $this->jwsLoader->verifyWithKeySet($jws, $this->signatureKeyset, 0)) {
            throw new JWTDecodeFailureException('decoding_error', 'An error occurred while trying to verify the JWT token.');
        }
        $payload = $jsonConverter->decode($jws->getPayload());
        $this->claimCheckerManager->check($payload);

        return $payload;
    }
530865
public function decode($token)
    {
        $decoded = json_decode($token, true);

        if (is_array($decoded) === true &&
            array_key_exists(self::KEY_USER_ID, $decoded) === true &&
            array_key_exists(self::KEY_SECRET, $decoded) === true
        ) {
            $token  = $decoded[self::KEY_SECRET];
            $userId = intval($decoded[self::KEY_USER_ID]);
            /** @var User $user */
            $user   = (new User())->query()->find($userId);

            if ($user !== null && $user->{User::FIELD_API_TOKEN} === $token) {
                $account = new Account($user, [Account::ATTR_ID => $userId]);

                $this->getLogger()->debug('Account authenticated.', [User::FIELD_ID => $userId]);

                return $account;
            }
        }

        return new Anonymous();
    }
859191
public static function getTokenName($token)
    {
        if (is_int($token[self::T_KEY])) {
            return token_name($token[self::T_KEY]);
        } else {
            return $token[self::T_KEY];
        }
    }
235512
public function filter($token)
    {
        // Apply replacements
        if ($this->tokenFrom) {
            $token = strtr($token, $this->tokenFrom, $this->tokenTo);
        }
        
        // If not case sensitive, convert to lowercase
        if (! $this->tokenCaseSensitive) {
            $token = strtolower($token);
        }
        
        // Filter out invalid chars
        $tokenLength   = strlen($token);
        $filteredToken = '';
        
        for ($tokenPos = 0; ($tokenPos < $tokenLength); $tokenPos++) {
            if (strpos($this->tokenChars, $token[$tokenPos]) !== false) {
                $filteredToken .= $token[$tokenPos];
            }
        }

        // Now check against the format for fixed chars
        $formatLength = strlen($this->tokenFormat);
        $tokenLength  = strlen($filteredToken);
        $tokenPos     = 0;
        $resultToken  = '';
        
        for ($formatPos = 0; ($formatPos < $formatLength) && ($tokenPos < $tokenLength); $formatPos++) {
            if ('\\' == $this->tokenFormat[$formatPos]) {
                $formatPos++;
                $resultToken .= $this->tokenFormat[$formatPos];

            } else {                
                $resultToken .= $filteredToken[$tokenPos];
                $tokenPos++;
            }
        }
        
        // Separate extra chars with a space and a questionmark
        if ($tokenPos < $tokenLength) {
            $resultToken .= ' ?' . substr($filteredToken, $tokenPos);
        }

        return $resultToken;
    }