### Create JWT in Tests with FrozenClock Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/quick-start.md Shows how to create JWTs in a testing environment using a FrozenClock for predictable timestamps. This ensures test stability by fixing the current time. The example uses FrozenClock to set a specific issue time and then issues a token. ```php issue( new Sha256(), $key, static fn ( Builder $builder, DateTimeImmutable $issuedAt ): Builder => $builder ); echo $token->claims()->get( RegisteredClaims::ISSUED_AT )->format(DateTimeImmutable::RFC3339); // 2022-06-24 22:51:10 ``` -------------------------------- ### Install lcobucci/jwt with Composer Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/installation.md Installs the lcobucci/jwt library as a project dependency using the Composer package manager. ```sh composer require lcobucci/jwt ``` -------------------------------- ### Include Composer Autoloader in PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/installation.md Includes Composer's autoloader file to enable the use of classes provided by the installed lcobucci/jwt library. ```php require 'vendor/autoload.php'; ``` -------------------------------- ### Issue JWT with Lcobucci JwtFacade Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/quick-start.md Demonstrates how to issue a JWT using the JwtFacade class. It specifies the algorithm (Sha256), an in-memory base64 encoded key, and a customization function to set issuer, permitted audience, and expiration time. The default expiration is 5 minutes, but this example extends it to 10 minutes. ```php issue( new Sha256(), $key, static fn ( Builder $builder, DateTimeImmutable $issuedAt ): Builder => $builder ->issuedBy('https://api.my-awesome-app.io') ->permittedFor('https://client-app.io') ->expiresAt($issuedAt->modify('+10 minutes')) ); var_dump($token->claims()->all()); echo $token->toString(); ``` -------------------------------- ### Install lcobucci/jwt using Composer Source: https://github.com/lcobucci/jwt/blob/6.0.x/README.md This snippet shows how to install the lcobucci/jwt library using Composer, the dependency manager for PHP. It is a straightforward command to add the package to your project. ```Shell composer require lcobucci/jwt ``` -------------------------------- ### Add lcobucci/clock as a dependency Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md This command adds the `lcobucci/clock` package as a production dependency. This is required if you were using it previously and are upgrading to versions where it's no longer installed by default. ```Shell composer require lcobucci/clock ``` -------------------------------- ### Update Builder API for immutability Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md Illustrates how to adapt code using the `Lcobucci\JWT\Builder` when it's marked as `@immutable`. The examples show how to chain method calls on the new `Builder` instance returned after each operation. ```PHP $token = (new JwtFacade())->issue( new Sha256(), $key, static function (\Lcobucci\JWT\Builder $builder, DateTimeImmutable $now): \Lcobucci\JWT\Builder { $builder = $builder->issuedBy('https://api.my-awesome-app.io'); $builder = $builder->permittedFor('https://client-app.io'); $builder = $builder->expiresAt($now->modify('+10 minutes')); return $builder; } ); ``` ```PHP $token = (new JwtFacade())->issue( new Sha256(), $key, static fn (\Lcobucci\JWT\Builder $builder, DateTimeImmutable $now): \Lcobucci\JWT\Builder => $builder->issuedBy('https://api.my-awesome-app.io') ->permittedFor('https://client-app.io') ->expiresAt($now->modify('+10 minutes')) ); ``` -------------------------------- ### Implement Custom Claims Formatter (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/extending-the-library.md Provides an example of implementing a custom claims formatter by adhering to the `Lcobucci\JWT\ClaimsFormatter` interface in PHP. This allows for custom formatting of JWT claims. ```PHP use Lcobucci\JWT\ClaimsFormatter; use Lcobucci\JWT\Configuration; use Serializable; final class ClaimSerializer implements ClaimsFormatter { /** @inheritdoc */ public function formatClaims(array $claims): array { foreach ($claims as $claim => $claimValue) { if ($claimValue instanceof Serializable) { $claims[$claim] = $claimValue->serialize(); } } return $claims; } } $config = $container->get(Configuration::class); assert($config instanceof Configuration); $builder = $config->builder(new ClaimSerializer()); ``` -------------------------------- ### Parse and Validate JWT with Lcobucci JwtFacade Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/quick-start.md Illustrates how to parse a JWT string and validate its signature and date claims using the JwtFacade. It employs constraints like SignedWith for signature verification and StrictValidAt for checking token validity against a specific time provided by FrozenClock. An invalid token or signature would result in an exception. ```php parse( $jwt, new Constraint\SignedWith(new Sha256(), $key), new Constraint\StrictValidAt( new FrozenClock(new DateTimeImmutable('2022-07-24 20:55:10+00:00')) ) ); var_dump($token->claims()->all()); ``` -------------------------------- ### Configure JWT Validation Constraints Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/configuration.md This example shows how to set base validation constraints for JWTs, including signature verification, validity period, and issuer. It utilizes PSR-20 clock implementations. ```php withValidationConstraints( new SignedWith($configuration->signer(), $configuration->signingKey()), new StrictValidAt(SystemClock::fromUTC()), new IssuedBy('https://api.my-awesome-company.com') ); ``` -------------------------------- ### Implement Custom Key (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/extending-the-library.md Provides an example of implementing a custom key by implementing the `Lcobucci\JWT\Signer\Key` interface in PHP. This custom key object is passed to signers for signature operations. ```PHP use Lcobucci\JWT\Signer\Key; final class KeyWithSomeMagicalProperties implements Key { // implement all methods } ``` -------------------------------- ### Configure JWT for Symmetric Algorithms Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/configuration.md Provides an example of configuring the JWT library for symmetric algorithms like HMAC SHA256. It demonstrates setting the signer and the secret key. ```php existsInDatabase($token->claims()->get('sub'))) { throw new ConstraintViolation('Token related to an unknown user'); } } private function existsInDatabase(string $userId): bool { // ... } } ``` -------------------------------- ### Retrieve JWT Token Data Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/issuing-tokens.md Shows how to access the headers and claims of an issued JWT token. After obtaining the token object, you can use methods like `headers()` and `claims()` to retrieve specific header parameters or claims, and then use `get()` to access their values. The string representation of the token can also be obtained. ```php issuedBy('http://example.com') ->withClaim('uid', 1) ->withHeader('foo', 'bar') ->getToken($algorithm, $signingKey); $token->headers(); // Retrieves the token headers $token->claims(); // Retrieves the token claims echo $token->headers()->get('foo'), PHP_EOL; // will print "bar" echo $token->claims()->get('iss'), PHP_EOL; // will print "http://example.com" echo $token->claims()->get('uid'), PHP_EOL; // will print "1" echo $token->toString(), PHP_EOL; // The string representation of the object is a JWT string ?> ``` -------------------------------- ### Initialize JWT Key from File Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/configuration.md Illustrates how to initialize an in-memory key by reading its content from a file path. This is suitable for managing keys stored in PEM or other file formats. ```php builder() ->issuedBy('http://example.com') ->withHeader('iss', 'http://example.com') ->permittedFor('http://example.org') ->identifiedBy('4f1g23a12aa') ->relatedTo('user123') ->issuedAt($now) ->canOnlyBeUsedAfter($now->modify('+1 minute')) ->expiresAt($now->modify('+1 hour')) ->withClaim('uid', 1) ->getToken($config->signer(), $config->signingKey()); ``` -------------------------------- ### Migrate Builder/Parser/Key Injection to Configuration Object (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md This diff shows how to refactor the injection of Builder, Signer, and Key dependencies to use the new Configuration object in lcobucci/jwt v4.x. The Configuration object acts as a service locator for JWT components, simplifying dependency injection. ```PHP config = $config; } public function issueToken(): Token { return $this->config->builder() ->identifiedBy(bin2hex(random_bytes(16))) ->getToken($this->config->signer(), $this->config->signingKey()); } } ``` -------------------------------- ### Migrate Key Usage to new Key Objects (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md This diff demonstrates the migration of `Lcobucci\JWT\Signer\Key` usage to the new `Lcobucci\JWT\Signer\Key\InMemory` class in lcobucci/jwt v4.x. It shows how to create Key objects from plain text, base64 encoded strings, and file contents using appropriate named constructors. ```PHP withBuilderFactory( static function (ClaimsFormatter $formatter): Builder { // This assumes `MyCustomBuilder` is an existing class return new MyCustomBuilder(new JoseEncoder(), $formatter); } ); ``` -------------------------------- ### Register Custom Builder Factory (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/extending-the-library.md Shows how to register a custom builder factory with the configuration object in PHP. This involves using a factory closure that returns an instance of a custom builder. ```PHP use Lcobucci\JWT\Builder; use Lcobucci\JWT\ClaimsFormatter; use Lcobucci\JWT\Configuration; $config = $container->get(Configuration::class); assert($config instanceof Configuration); $configuration = $config->withBuilderFactory( static function (ClaimsFormatter $formatter): Builder { return new MyCustomTokenBuilder($formatter); } ); ``` -------------------------------- ### Replace unsecured signer with Blake2b Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md Shows how to replace the usage of `Configuration::forUnsecuredSigner()` with a symmetric signer, specifically `Signer\Blake2b()`, when migrating away from the 'none' algorithm. This is recommended for more secure usage. ```PHP issuedBy('http://example.com') // Configures the audience (aud claim) ->permittedFor('http://example.org') // Configures the subject of the token (sub claim) ->relatedTo('component1') // Configures the id (jti claim) ->identifiedBy('4f1g23a12aa') // Configures the time that the token was issue (iat claim) ->issuedAt($now) // Configures the time that the token can be used (nbf claim) ->canOnlyBeUsedAfter($now->modify('+1 minute')) // Configures the expiration time of the token (exp claim) ->expiresAt($now->modify('+1 hour')) // Configures a new claim, called "uid" ->withClaim('uid', 1) // Configures a new header, called "foo" ->withHeader('foo', 'bar') // Builds a new token ->getToken($algorithm, $signingKey); echo $token->toString(); ?> ``` -------------------------------- ### Configure JWT for Asymmetric Algorithms Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/configuration.md Shows how to configure the JWT library for asymmetric algorithms like RSA SHA256. It includes setting the signer, private key, and public key. ```php config = $config; } public function authenticate(string $jwt): void { $token = $this->config->parser()->parse($jwt); if (! $this->config->validator()->validate($token, ...$this->config->validationConstraints())) { throw new InvalidArgumentException('Invalid token provided'); } } } ``` -------------------------------- ### Register Custom Parser (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/extending-the-library.md Demonstrates registering a custom parser instance with the configuration object in PHP. This allows the library to use the custom parser for JWT string conversion. ```PHP use Lcobucci\JWT\Configuration; $config = $container->get(Configuration::class); assert($config instanceof Configuration); $configuration = $config->withParser(new MyCustomTokenParser()); ``` -------------------------------- ### Implement Custom Signer (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/extending-the-library.md Shows how to implement a custom signer by adhering to the `Lcobucci\JWT\Signer` interface in PHP. This is used for creating and verifying custom algorithm signatures. ```PHP use Lcobucci\JWT\Signer; final class SignerForAVeryCustomizedAlgorithm implements Signer { // implement all methods } ``` -------------------------------- ### Customize JWT Parser Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/configuration.md Shows how to customize the JWT parser by providing a custom parser implementation. This is useful for handling custom token parsing logic. ```php withParser(new MyParser()); ``` -------------------------------- ### PHP: Add Multiple Audiences to JWT with permittedFor() arguments Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md Demonstrates adding multiple audiences to a JWT in a single call to `permittedFor()` by passing them as separate arguments. ```PHP builder() ->permittedFor('one', 'two', 'three') ->getToken($config->signer(), $config->signingKey()); ``` -------------------------------- ### Require lcobucci/jwt ^4.3 Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md This command updates the lcobucci/jwt library to the latest 4.3.x version, preparing for the v5.0.0 upgrade. It's recommended to run tests after this update and address any deprecated method calls. ```Shell composer require lcobucci/jwt ^4.3 ``` -------------------------------- ### Implement Custom Token Parser (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/extending-the-library.md Illustrates how to create a custom token parser by implementing the `Lcobucci\JWT\Parser` interface in PHP. This enables custom logic for converting JWT strings into token objects. ```PHP use Lcobucci\JWT\Parser; final class MyCustomTokenParser implements Parser { // implement all methods } ``` -------------------------------- ### BLAKE2b Signing - PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/supported-algorithms.md Implements BLAKE2b keyed hash for JWT signing. Requires a key length of at least 256 bits. Note: This is not a JWT standard algorithm and may not be supported by other libraries. ```php namespace Lcobucci\JWT\Signer; use Lcobucci\JWT\Token\Plain; class Blake2b implements KeyAuth { public function algorithmId(): string { return 'BLAKE2B'; } public function signature(Plain $token, Key $key): string { return hash('blake2b', $token->getPayload(), $key->get()); } } ``` -------------------------------- ### PHP: Add Multiple Audiences to JWT with argument unpacking Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md Shows how to add multiple audiences to a JWT using `permittedFor()` with argument unpacking from an array. ```PHP builder() ->permittedFor(...['one', 'two', 'three']) ->getToken($config->signer(), $config->signingKey()); ``` -------------------------------- ### Register Custom Validator (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/extending-the-library.md Demonstrates registering a custom validator instance with the configuration object in PHP. This enables the library to use the custom validator for token validation constraints. ```PHP use Lcobucci\JWT\Configuration; $config = $container->get(Configuration::class); assert($config instanceof Configuration); $configuration = $config->withValidator(new MyCustomTokenValidator()); ``` -------------------------------- ### Issue JWT with Blake2b Algorithm - PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/rotating-keys.md This snippet demonstrates how to issue a JWT using the Blake2b symmetric algorithm with the lcobucci/jwt library. It updates the `JwtFacade` to use `SignerBlake2b` and `InMemory::base64Encoded` for the key, replacing the previous `Sha256` and `InMemory::plainText`. ```PHP issue( new Signer\Blake2b(), InMemory::base64Encoded( 'GOu4rLyVCBxmxP+sbniU68ojAja5PkRdvv7vNvBCqDQ=' ), static fn (Builder $builder): Builder => $builder ->issuedBy('https://api.my-awesome-app.io') ->permittedFor('https://client-app.io') ); ``` -------------------------------- ### Implement Custom Token Validator (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/extending-the-library.md Illustrates how to create a custom token validator by implementing the `Lcobucci\JWT\Validator` interface in PHP. This allows for custom validation constraint logic. ```PHP use Lcobucci\JWT\Validator; final class MyCustomTokenValidator implements Validator { // implement all methods } ``` -------------------------------- ### EdDSA Signature Signing - PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/supported-algorithms.md Implements EdDSA signature algorithms for JWT signing. Requires a key length of at least 256 bits. This is an asymmetric algorithm. ```php namespace Lcobucci\JWT\Signer; use Lcobucci\JWT\Token\Plain; class Eddsa implements KeyAuth { public function algorithmId(): string { return 'EdDSA'; } public function signature(Plain $token, Key $key): string { $signature = ''; openssl_sign($token->getPayload(), $signature, $key->get(), OPENSSL_ALGO_ยป; // EdDSA is not directly supported by openssl_sign with a specific constant return $signature; } } ``` -------------------------------- ### Adapt Token Manipulation to New Token API (PHP) Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md This snippet illustrates the changes required to adapt code that interacts with JWT tokens using the new Token API in lcobucci/jwt v4. It highlights the differences in accessing headers and claims, and how to convert a token to its string representation. ```PHP headers()->all() $token->headers()->has('typ') $token->headers()->get('typ') $token->claims()->all() $token->claims()->has('iss') $token->claims()->get('iss') echo $token->toString(); ``` -------------------------------- ### RSASSA-PKCS1-v1_5 SHA-256 Signing - PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/supported-algorithms.md Implements RSASSA-PKCS1-v1_5 using SHA-256 for JWT signing. Requires a key length of at least 2048 bits. This is an asymmetric algorithm. ```php namespace Lcobucci\JWT\Signer\Rsa; use Lcobucci\JWT\Signer; use Lcobucci\JWT\Token\Plain; class Sha256 implements Signer\KeyAuth\RsaSsaPkcs1 { public function algorithmId(): string { return 'RS256'; } public function signature(Plain $token, Signer\Key $key): string { $signature = ''; openssl_sign($token->getPayload(), $signature, $key->get(), OPENSSL_ALGO_SHA256); return $signature; } } ``` -------------------------------- ### Parse JWT Token in PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/parsing-tokens.md This snippet demonstrates how to parse a JWT token string using the `Parser` class from the Lcobucci/JWT library. It includes error handling for common decoding issues and shows how to access claims from the parsed token. ```php parse( 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' . 'eyJzdWIiOiIxMjM0NTY3ODkwIn0.' . '2gSBz9EOsQRN9I-3iSxJoFt7NtgV6Rm0IL6a8CAwl3Q' ); } catch (CannotDecodeContent | InvalidTokenStructure | UnsupportedHeaderFound $e) { echo 'Oh no, an error: ' . $e->getMessage(); } assert($token instanceof UnencryptedToken); echo $token->claims()->get('sub'), PHP_EOL; // will print "1234567890" ``` -------------------------------- ### RSASSA-PKCS1-v1_5 SHA-384 Signing - PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/supported-algorithms.md Implements RSASSA-PKCS1-v1_5 using SHA-384 for JWT signing. Requires a key length of at least 2048 bits. This is an asymmetric algorithm. ```php namespace Lcobucci\JWT\Signer\Rsa; use Lcobucci\JWT\Signer; use Lcobucci\JWT\Token\Plain; class Sha384 implements Signer\KeyAuth\RsaSsaPkcs1 { public function algorithmId(): string { return 'RS384'; } public function signature(Plain $token, Signer\Key $key): string { $signature = ''; openssl_sign($token->getPayload(), $signature, $key->get(), OPENSSL_ALGO_SHA384); return $signature; } } ``` -------------------------------- ### PHP: Assert Token Validity with Lcobucci/JWT Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/validating-tokens.md Demonstrates how to use the `assert()` method from Lcobucci\JWT\Validator to validate a token against a set of constraints. This method collects all violations and throws a `RequiredConstraintsViolated` exception if any constraint fails. ```php parse( 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' . 'eyJzdWIiOiIxMjM0NTY3ODkwIn0.' . '2gSBz9EOsQRN9I-3iSxJoFt7NtgV6Rm0IL6a8CAwl3Q' ); $validator = new Validator(); try { $validator->assert($token, new RelatedTo('1234567891')); // doesn't throw an exception $validator->assert($token, new RelatedTo('1234567890')); } catch (RequiredConstraintsViolated $e) { // list of constraints violation exceptions: var_dump($e->violations()); } ``` -------------------------------- ### ECDSA P-256 SHA-256 Signing - PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/supported-algorithms.md Implements ECDSA using P-256 and SHA-256 for JWT signing. Requires a key length of exactly 256 bits. This is an asymmetric algorithm. ```php namespace Lcobucci\JWT\Signer\Ecdsa; use Lcobucci\JWT\Signer; use Lcobucci\JWT\Token\Plain; class Sha256 implements Signer\KeyAuth\Ecdsa { public function algorithmId(): string { return 'ES256'; } public function signature(Plain $token, Signer\Key $key): string { $signature = ''; openssl_sign($token->getPayload(), $signature, $key->get(), OPENSSL_ALGO_SHA256); return $signature; } } ``` -------------------------------- ### RSASSA-PKCS1-v1_5 SHA-512 Signing - PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/supported-algorithms.md Implements RSASSA-PKCS1-v1_5 using SHA-512 for JWT signing. Requires a key length of at least 2048 bits. This is an asymmetric algorithm. ```php namespace Lcobucci\JWT\Signer\Rsa; use Lcobucci\JWT\Signer; use Lcobucci\JWT\Token\Plain; class Sha512 implements Signer\KeyAuth\RsaSsaPkcs1 { public function algorithmId(): string { return 'RS512'; } public function signature(Plain $token, Signer\Key $key): string { $signature = ''; openssl_sign($token->getPayload(), $signature, $key->get(), OPENSSL_ALGO_SHA512); return $signature; } } ``` -------------------------------- ### PHP: Add Multiple Audiences to JWT using permittedFor() Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md Illustrates how to specify multiple audiences for a JWT using the `permittedFor()` method in the JWT Builder, allowing for multiple calls. ```PHP builder() ->permittedFor('one') ->permittedFor('two') ->permittedFor('three') ->getToken($config->signer(), $config->signingKey()); ``` -------------------------------- ### Update lcobucci/jwt to v3.4 Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md This command updates the lcobucci/jwt library to the latest 3.4.x version using Composer. It's the first step in the migration process, followed by running tests and fixing deprecation notices. ```Shell composer require lcobucci/jwt ^3.4 ``` -------------------------------- ### Parse and Validate JWT with Multiple Signers - PHP Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/rotating-keys.md This snippet shows how to parse and validate a JWT that may have been signed with different algorithms and keys. It uses `Constraint\SignedWithOneInSet` to specify multiple `Constraint\SignedWithUntilDate` instances, allowing tokens signed with Blake2b until a future date and Sha256 until a past date to be accepted. ```PHP parse($jwt, ...$validationConstraints); ``` -------------------------------- ### Update lcobucci/jwt to v4.0 Source: https://github.com/lcobucci/jwt/blob/6.0.x/docs/upgrading.md This command updates the lcobucci/jwt library to the latest 4.x version using Composer. After addressing deprecations in v3.4, this step allows for adopting new features and further code adaptations. ```Shell composer require lcobucci/jwt ^4.0 ```