lcobucci/jwt

repository·6.0.x·Indexed 27 days ago

https://github.com/lcobucci/jwt

A 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.

Tokens
13.2K
Snippets
31
Records
43
Agent score
91%

What's inside lcobucci/jwt

  1. Implement a custom Signer

    6.0.x

    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
    }
  2. Migrate from v3.x to v4.x

    6.0.x

    Upgrading from v3.x to v4.x involves several breaking changes. Follow this strategy to minimize issues:

    1. Update to the latest 3.4.x version: Use composer require lcobucci/jwt ^3.4.
    2. Fix Deprecations: Run your tests and fix all E_USER_DEPRECATED notices. It is recommended to run tests with E_ALL enabled. Tools like phpstan/phpstan-deprecation-rules can help identify these.
    3. Upgrade to 4.x: Once the 3.4.x version is clean of deprecations, run composer require lcobucci/jwt ^4.0.
    4. Adapt to 4.x changes: Some deprecation notices from 3.4 may require further code adjustments once on 4.0.
  3. Customize Configuration components

    6.0.x

    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.
  4. Inject the Configuration object (v4.x)

    6.0.x

    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());
         }
     }
  5. Implement a custom Claims formatter

    6.0.x

    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());
  6. Implement a custom Validator

    6.0.x

    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());
  7. Parse and validate tokens with JwtFacade#parse()

    6.0.x

    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());