Overview of lcobucci/jwt
6.0.xlcobucci/jwt is a framework-agnostic PHP library used to issue, parse, and validate JSON Web Tokens (JWT) in compliance with [RFC 7519].repository·6.0.x·Indexed 27 days ago
https://github.com/lcobucci/jwtA framework-agnostic PHP library for working with JSON Web Tokens (JWT) and JSON Web Signatures (JWS) in compliance with RFC 7519. It provides tools to issue, parse, and validate tokens, featuring a flexible Configuration system for symmetric and asymmetric algorithms, as well as interfaces to implement custom builders, parsers, signers, validators, and validation constraints.
lcobucci/jwt is a framework-agnostic PHP library used to issue, parse, and validate JSON Web Tokens (JWT) in compliance with [RFC 7519].The signer defines how signatures are created and verified. Implement the Lcobucci\JWT\Signer interface. Once implemented, you can pass an instance of your signer when creating a Configuration object, issuing a token, or validating a token.
use Lcobucci\JWT\Signer;
final class SignerForAVeryCustomizedAlgorithm implements Signer
{
// implement all methods
}Install the library using Composer to start working with JSON Web Tokens (JWT) and JSON Web Signatures (JWS) based on RFC 7519.
composer require lcobucci/jwtAdd lcobucci/jwt as a dependency to your project using Composer by running the following command in your terminal.
composer require lcobucci/jwtUpgrading from v3.x to v4.x involves several breaking changes. Follow this strategy to minimize issues:
composer require lcobucci/jwt ^3.4.E_USER_DEPRECATED notices. It is recommended to run tests with E_ALL enabled. Tools like phpstan/phpstan-deprecation-rules can help identify these.composer require lcobucci/jwt ^4.0.You can customize the library setup by using setter methods on the Lcobucci\JWT\Configuration instance.
Important: You must call all setters before invoking any getters. If you call a getter first, the library will use default implementations and your customizations will be ignored.
Available customization methods:
withBuilderFactory(callable $factory): Provides a custom factory for creating the token builder.withParser(Parser $parser): Provides a custom token parser.withValidator(Validator $validator): Provides a custom token validator.withValidationConstraints(...$constraints): Configures the base constraints used during validation.In v4.0, instead of injecting individual Builder, Parser, or Signer components, you should inject a single Lcobucci\[JWT]\Configuration object. This object acts as a service locator for all JWT-related dependencies, simplifying dependency injection in your application.
<?php
declare(strict_types=1);
namespace Me\MyApp\Authentication;
-use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Configuration;
-use Lcobucci\JWT\Signer;
-use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Token;
use function bin2hex;
use function random_bytes;
final class JwtIssuer
{
- private Builder $builder;
- private Signer $signer;
- private Key $key;
-
- public function __construct(Builder $builder, Signer $signer, Key $key)
- {
- $this->builder = $builder;
- $this->signer = $signer;
- $this->key = $key;
- }
+ private Configuration $config;
+
+ public function __construct(Configuration $config)
+ {
+ $this->config = $config;
+ }
public function issueToken(): Token
{
- return $this->builder
+ return $this->config->builder()
->identifiedBy(bin2hex(random_bytes(16)))
- ->getToken($this->signer, $this->key);
+ ->getToken($this->config->signer(), $this->config->signingKey());
}
}Custom claims formatters allow you to control how claims are processed before being encoded. Implement the Lcobucci\JWT\ClaimsFormatter interface to create your own. You can also use Lcobucci\JWT\Encoding\ChainedFormatter to combine multiple formatters. To use your custom formatter, pass it to the builder() method of your Configuration instance.
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());The validator defines how validation constraints are applied to tokens. Implement the Lcobucci\JWT\Validator interface and register it in your Configuration using the withValidator() method.
use Lcobucci\JWT\Validator;
use Lcobucci\JWT\Configuration;
final class MyCustomTokenValidator implements Validator
{
// implement all methods
}
$config = $container->get(Configuration::class);
assert($config instanceof Configuration);
$configuration = $config->withValidator(new MyCustomTokenValidator());To use the classes provided by the library, you must include the Composer autoloader in your application entry point.
require 'vendor/autoload.php';The Lcobucci\JWT\JwtFacade#parse() method quickly parses a JWT string and verifies its signature and date claims. It throws an exception if the token is in an unexpected state (e.g., invalid signature or expired).
Note: When using this in production, use SystemClock to ensure date claims are verified against the actual current time. Use FrozenClock only for testing or deterministic scenarios.
<?php
declare(strict_types=1);
namespace MyApp;
require 'vendor/autoload.php';
use DateTimeImmutable;
use Lcobucci\Clock\FrozenClock; // If you prefer, other PSR-20 implementations may also be used
// (https://packagist.org/providers/psr/clock-implementation)
use Lcobucci\JWT\JwtFacade;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Validation\Constraint;
use function var_dump;
$jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NTg2OTYwNTIsIm5iZiI6MT'
. 'Y1ODY5NjA1MiwiZXhwIjoxNjU4Njk2NjUyLCJpc3MiOiJodHRwczovL2FwaS5teS1hd2Vzb'
. '21lLWFwcC5pbyIsImF1ZCI6Imh0dHBzOi8vY2xpZW50LWFwcC5pbyJ9.yzxpjyq8lXqMgaN'
. 'rMEOLUr7R0brvhwXx0gp56uWEIfc';
$key = InMemory::base64Encoded(
'hiG8DlOKvtih6AxlZn5XKImZ06yu8I3mkOzaJrEuW8yAv8Jnkw330uMt8AEqQ5LB'
);
$token = (new JwtFacade())->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());