public function testWithCustomHeaders() { $encoded = Jwt::encode('foobar', $alg = new HS256Algorithm('secret'), ['header' => ['foo' => 'bar']]); $decoded = Jwt::decode($encoded, ['algorithm' => $alg, 'with_head' => true]); $this->assertInstanceOf('Jwt\\Token', $decoded); $this->assertEquals(['typ' => 'JWT', 'alg' => 'HS256', 'foo' => 'bar'], $decoded->getHeader()->toArray()); }
<?php /* * This file is part of Jwt for Php. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once __DIR__ . '/../vendor/autoload.php'; use Jwt\Jwt; use Jwt\Algorithm\RS256Algorithm; $privateKey = __DIR__ . '/key.pem'; $publicKey = __DIR__ . '/key.pub'; $token = Jwt::encode('string', $alg = new RS256Algorithm($privateKey, $publicKey)); echo $token; // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoic3RyaW5nIn0.RncJbCyf4zd0pu1N02u_rKwEezkmd94r3i5sWLk1ceU // decode, you must passed allowed algorithm(s) to prevent attackers to control the choice of algorithm $decoded = Jwt::decode($token, ['algorithm' => $alg]); echo $decoded['data']; // 'string'
<?php /* * This file is part of Jwt for Php. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once __DIR__ . '/../vendor/autoload.php'; use Jwt\Jwt; use Jwt\Algorithm\NoneAlgorithm; $token = Jwt::encode('string', new NoneAlgorithm()); echo $token;
/** * @param $value * @return null * @throws SettingParameterNullException * @throws \Jwt\Exception\SignatureInvalidException */ public static function decodeVal($value) { if (!$value) { return null; } $decoded = Jwt::decode($value, ['algorithm' => new HS256Algorithm(self::getSecretKey())]); return $decoded['data']; }
* file that was distributed with this source code. */ require_once __DIR__ . '/../vendor/autoload.php'; use Jwt\Jwt; use Jwt\Algorithm\HS256Algorithm; use Jwt\Exception\VerificationException; $payload = [Jwt::CLAIM_EXPIRATION => strtotime('1 day'), Jwt::CLAIM_ISSUER => 'my-web-app', 'user' => 'administrator']; $token = Jwt::encode($payload, $alg = new HS256Algorithm('secret')); // Decode with verification of the payload // Expiration, and Not before claims are verified automatically // we will verify the token when decoding $verify = [Jwt::CLAIM_ISSUER => 'my-web-app', 'user' => function ($value) { if ($value === 'administrator') { return true; } return false; }]; try { $decoded = Jwt::decode($token, ['algorithm' => $alg, 'verify' => $verify]); } catch (VerificationException $e) { // something is wrong with the token // do something! switch ($e->getCode()) { case VerificationException::CLAIM_IS_MISSING: // claim is missing break; case VerificationException::CLAIM_VALUE_IS_INVALID: // invalid claim value break; } }