1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
|
# Upgrading steps
Here we'll keep a list of all steps you need to take to make sure your code is compatible with newer versions.
## v4.x to v5.x
The release `v5.0.0` is a modernised version of the library, which requires PHP 8.1+ and drops all the deprecated components.
We're adding a few deprecation annotations on the version `v4.3.0`.
So, before going to `v5.0.0` please update to the latest 4.3.x version using composer:
```sh
composer require lcobucci/jwt ^4.3
```
Then run your tests and change all calls to deprecated methods, even if they are not triggering any notices.
Tools like [`phpstan/phpstan-deprecation-rules`](https://github.com/phpstan/phpstan-deprecation-rules) can help finding them.
### Removal of `Ecdsa::create()`
To promote symmetry on the instantiation of all algorithms (signers), we're dropping the named constructor in favour of the constructor.
If you are using any variant of ECDSA, please change your code following this example:
```diff
<?php
declare(strict_types=1);
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key\InMemory;
require 'vendor/autoload.php';
$configuration = Configuration::forAsymmetricSigner(
- Signer\Ecdsa\Sha256::create(),
+ new Signer\Ecdsa\Sha256(),
InMemory::file(__DIR__ . '/my-private-key.pem'),
InMemory::base64Encoded('mBC5v1sOKVvbdEitdSBenu59nfNfhwkedkJVNabosTw=')
// You may also override the JOSE encoder/decoder if needed
// by providing extra arguments here
);
```
### Removal of `none` algorithm
To promote a more secure usage of the library and prevent misuse we decided to deviate from the RFC and drop `none`, which means that the following components are being removed:
* `Lcobucci\JWT\Configuration::forUnsecuredSigner()`
* `Lcobucci\JWT\Signer\Key\InMemory::empty()`
* `Lcobucci\JWT\Signer\None`
* `Lcobucci\JWT\Token\Signature::fromEmptyData()`
If you're relying on it and still want to have that on your system, please create your own implementation.
If you're using it because it's "fast", please look into adoption the non-standard Blake2b implementation:
```diff
<?php
declare(strict_types=1);
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key\InMemory;
require 'vendor/autoload.php';
-$configuration = Configuration::forUnsecuredSigner();
+$configuration = Configuration::forSymmetricSigner(
+ new Signer\Blake2b(),
+ InMemory::base64Encoded('MpQd6dDPiqnzFSWmpUfLy4+Rdls90Ca4C8e0QD0IxqY=')
+);
```
### `Builder` API is now `@immutable`
`\Lcobucci\JWT\Builder` interface alongside with its default implementation `\Lcobucci\JWT\Token\Builder` are now marked `@immutable`.
If you are using it for example with the `JwtFacade` ensure now to use the returned new `Builder` instance:
```diff
$token = (new JwtFacade())->issue(
new Sha256(),
$key,
static function (
Builder $builder,
DateTimeImmutable $now
): Builder {
- $builder->issuedBy('https://api.my-awesome-app.io');
- $builder->permittedFor('https://client-app.io');
- $builder->expiresAt($now->modify('+10 minutes'));
+ $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;
}
);
```
Or:
```diff
$token = (new JwtFacade())->issue(
new Sha256(),
$key,
- static function (
+ static fn (
Builder $builder,
DateTimeImmutable $now
- ): Builder {
- $builder->issuedBy('https://api.my-awesome-app.io');
- $builder->permittedFor('https://client-app.io');
- $builder->expiresAt($now->modify('+10 minutes'));
-
- return $builder;
- }
+ ): Builder => $builder->issuedBy('https://api.my-awesome-app.io')
+ ->permittedFor('https://client-app.io')
+ ->expiresAt($now->modify('+10 minutes'))
);
```
### `lcobucci/clock` is not installed by default anymore
Thanks to [PSR-20](https://www.php-fig.org/psr/psr-20/), users can more easily plug-in other [clock implementations](https://packagist.org/providers/psr/clock-implementation) if they choose to do so.
If you like and were already using `lcobucci/clock` on your system, you're required to explicitly add it as a production dependency:
```sh
composer require lcobucci/clock
```
## v3.x to v4.x
The `v4.0.0` aggregates about 5 years of work and contains **several BC-breaks**.
We're building on the version `v3.4.0` a forward compatibility layer to help users to migrate to `v4.0.0`.
To help on the migration process, all deprecated components are being marked with `@deprecated` and deprecated behaviour will trigger a `E_USER_DEPRECATED` error.
However, you can also find here the instructions on how to make your code compatible with both versions.
### General migration strategy
Update your existing software to the latest 3.4.x version using composer:
```sh
composer require lcobucci/jwt ^3.4
```
Then run your tests and fix all deprecation notices.
Also change all calls to deprecated methods, even if they are not triggering any notices.
Tools like [`phpstan/phpstan-deprecation-rules`](https://github.com/phpstan/phpstan-deprecation-rules) can help finding them.
Note that PHPUnit tests will only fail if you have the `E_USER_DEPRECATED` error level activated - it is a good practice to run tests using `E_ALL`.
Data providers that trigger deprecation messages will not fail tests at all, only print the message to the console.
Make sure you do not see any of them before you continue.
Now you can upgrade to the latest 4.x version:
```sh
composer require lcobucci/jwt ^4.0
```
Remember that some deprecation messages from the 3.4 version may have notified you that things still are different in 4.0, so you may find you need to adapt your own code once more at this stage.
While you are at it, consider using the new configuration object.
The details are listed below.
### Inject the configuration object instead of builder/parser/key
This object serves as a small service locator that centralises the JWT-related dependencies.
The main goal is to simplify the injection of our components into downstream code.
This step is quite important to at least have a single way to initialise the JWT components, even if the configuration object is thrown away.
Check an example of how to migrate the injection of builder+signer+key to configuration object below:
```diff
<?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());
}
}
```
You can find more information on how to use the configuration object, [here](configuration.md).
### Use new `Key` objects
`Lcobucci\JWT\Signer\Key` has been converted to an interface in `v4.0`.
We provide `Lcobucci\JWT\Signer\Key\InMemory`, a drop-in replacement of the behaviour for `Lcobucci\JWT\Signer\Key` in `v3.x`.
You will need to pick the appropriated named constructor to migrate your code:
```diff
<?php
declare(strict_types=1);
namespace Me\MyApp\Authentication;
-use Lcobucci\JWT\Signer\Key;
+use Lcobucci\JWT\Signer\Key\InMemory;
-
-use function base64_decode;
// Key from plain text
-$key = new Key('a-very-secure-key');
+$key = InMemory::plainText('a-very-secure-key');
// Key from base64 encoded string
-$key = new Key(base64_decode('YS12ZXJ5LXNlY3VyZS1rZXk=', true));
+$key = InMemory::base64Encoded('YS12ZXJ5LXNlY3VyZS1rZXk=');
// Key from file contents
-$key = new Key('file:///var/secrets/my-private-key.pem');
+$key = InMemory::file('/var/secrets/my-private-key.pem');
```
### Use the new `Builder` API
There are 4 main differences on the new API:
1. Token configuration methods were renamed
1. Signature is created via `Builder#getToken()` (instead of `Builder#sign()`)
1. `DateTimeImmutable` objects are now used for the registered claims with dates, which are by default encoded as floats with microseconds as precision
1. Headers should be replicated manually - whenever necessary
Here's the migration:
```diff
<?php
declare(strict_types=1);
namespace Me\MyApp\Authentication;
+use DateTimeImmutable;
-use Lcobucci\JWT\Builder;
+use Lcobucci\JWT\Configuration;
+use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Hmac\Sha256;
-
-use function time;
-$now = time();
+$now = new DateTimeImmutable();
+$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText('testing'));
-$token = (new Builder())
+$token = $config->builder()
- ->setIssuer('http://example.com', true)
+ ->issuedBy('http://example.com')
+ ->withHeader('iss', 'http://example.com')
- ->setAudience('http://example.org')
+ ->permittedFor('http://example.org')
- ->setId('4f1g23a12aa')
+ ->identifiedBy('4f1g23a12aa')
- ->setSubject('user123')
+ ->relatedTo('user123')
- ->setIssuedAt($now)
+ ->issuedAt($now)
- ->setNotBefore($now + 60)
+ ->canOnlyBeUsedAfter($now->modify('+1 minute'))
- ->setExpiration($now + 3600)
+ ->expiresAt($now->modify('+1 hour'))
- ->set('uid', 1)
+ ->withClaim('uid', 1)
- ->sign(new Sha256(), 'testing')
- ->getToken();
+ ->getToken($config->signer(), $config->signingKey());
```
#### Date precision
If you want to continue using Unix timestamps, you can use the `withUnixTimestampDates()`-formatter:
```diff
<?php
-$builder = new Builder());
+$builder = $config->builder(ChainedFormatter::withUnixTimestampDates());
```
#### Support for multiple audiences
Even though we didn't officially support multiple audiences, it was technically possible to achieve that by manually setting the `aud` claim to an array with multiple strings.
If you parse a token with 3.4, and read its contents with `\Lcobucci\JWT\Token#getClaim()` or`\Lcobucci\JWT\Token#getClaims()`, you will only get the first element of such an array back.
If the audience claim does only contain a string, or only contains one string in the array, nothing changes.
Please [upgrade to the new Token API](#use-the-new-token-api) for accessing claims in order to get the full audience array again (e.g. call `Token#claims()->get('aud')`).
When creating a token, use the new method `Builder#permittedFor()` as detailed below.
##### Multiple calls to `Builder#permittedFor()`
```diff
<?php
declare(strict_types=1);
namespace Me\MyApp\Authentication;
-use Lcobucci\JWT\Builder;
+use Lcobucci\JWT\Configuration;
+use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Hmac\Sha256;
+$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText('testing'));
-$token = (new Builder())
+$token = $config->builder()
- ->withClaim('aud', ['one', 'two', 'three'])
+ ->permittedFor('one')
+ ->permittedFor('two')
+ ->permittedFor('three')
- ->sign(new Sha256(), 'testing')
- ->getToken();
+ ->getToken($config->signer(), $config->signingKey());
```
##### Single call to `Builder#permittedFor()` with multiple arguments
```diff
<?php
declare(strict_types=1);
namespace Me\MyApp\Authentication;
-use Lcobucci\JWT\Builder;
+use Lcobucci\JWT\Configuration;
+use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Hmac\Sha256;
+$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText('testing'));
-$token = (new Builder())
+$token = $config->builder()
- ->withClaim('aud', ['one', 'two', 'three'])
+ ->permittedFor('one', 'two', 'three')
- ->sign(new Sha256(), 'testing')
- ->getToken();
+ ->getToken($config->signer(), $config->signingKey());
```
##### Single call to `Builder#permittedFor()` with argument unpacking
```diff
<?php
declare(strict_types=1);
namespace Me\MyApp\Authentication;
-use Lcobucci\JWT\Builder;
+use Lcobucci\JWT\Configuration;
+use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Hmac\Sha256;
+$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText('testing'));
-$token = (new Builder())
+$token = $config->builder()
- ->withClaim('aud', ['one', 'two', 'three'])
+ ->permittedFor(...['one', 'two', 'three'])
- ->sign(new Sha256(), 'testing')
- ->getToken();
+ ->getToken($config->signer(), $config->signingKey());
```
### Replace `Token#verify()` and `Token#validate()` with Validation API
These methods were quite limited and brings multiple responsibilities to the `Token` class.
On `v4.0` we provide another component to validate tokens, including their signature.
Here's an example of how to modify that logic (considering [constraints have been configured](configuration.md#customisation)):
```diff
<?php
declare(strict_types=1);
namespace Me\MyApp\Authentication;
use InvalidArgumentException;
+use Lcobucci\JWT\Configuration;
-use Lcobucci\JWT\Signer;
-use Lcobucci\JWT\Signer\Key;
-use Lcobucci\JWT\Parser;
-use Lcobucci\JWT\ValidationData;
final class AuthenticateJwt
{
- private Parser $parser;
- private Signer $signer;
- private Key $key;
+ private Configuration $config;
- public function __construct(Parser $parser, Signer $signer, Key $key)
+ public function __construct(Configuration $config)
{
- $this->parser = $parser;
- $this->signer = $signer;
- $this->key = $key;
+ $this->config = $config;
}
public function authenticate(string $jwt): void
{
- $token = $this->parser->parse($jwt);
+ $token = $this->config->parser()->parse($jwt);
- if (! $token->validate(new ValidationData()) || $token->verify($this->signer, $this->key)) {
+ if (! $this->config->validator()->validate($token, ...$this->config->validationConstraints())) {
throw new InvalidArgumentException('Invalid token provided');
}
}
}
```
Check [here](validating-tokens.md) for more information on how to validate tokens and what are the built-in constraints.
### Use the new `Token` API
There some important differences on this new API:
1. We no longer use the `Lcobucci\JWT\Claim` objects
1. Headers and claims are now represented as `Lcobucci\JWT\Token\DataSet`
1. Different methods should be used to retrieve a header/claim
1. No exception is thrown when accessing missing header/claim, the default argument is always used
1. Tokens should be explicitly casted to string via method
Your code should be adapted to manipulate tokens like this:
```diff
<?php
declare(strict_types=1);
namespace Me\MyApp\Authentication;
// we assume here that $token is a valid parsed/created token
-$token->getHeaders()
+$token->headers()->all()
-$token->hasHeader('typ')
+$token->headers()->has('typ')
-$token->getHeader('typ')
+$token->headers()->get('typ')
-$token->getClaims()
+$token->claims()->all()
-$token->hasClaim('iss')
+$token->claims()->has('iss')
-$token->getClaim('iss')
+$token->claims()->get('iss')
-echo (string) $token;
+echo $token->toString();
```
|