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\HS256Algorithm; use Jwt\Exception\BeforeValidException; $payload = [Jwt::CLAIM_NOT_BEFORE => strtotime('1 day'), 'data' => 'my data']; $token = Jwt::encode($payload, $alg = new HS256Algorithm('secret')); try { $token = Jwt::decode($token, ['algorithm' => $alg]); } catch (BeforeValidException $e) { throw $e; // Handle invalid token, e.g. logout user or deny access }
<?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\HS256Algorithm; $token = Jwt::encode('string', $alg = new HS256Algorithm('secret')); 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'
/** * @param $value * @return string * @throws SettingParameterNullException */ public static function encodeVal($value) { $value = Jwt::encode($value, ['algorithm' => new HS256Algorithm(self::getSecretKey())]); return $value; }
<?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;