Skip to content

Commit aa9f058

Browse files
authored
Merge pull request #548 from lcobucci/final-preparations-for-3.4
Final preparations for 3.4
2 parents 1e5add9 + 5d1dcb1 commit aa9f058

27 files changed

+826
-294
lines changed

README.md

Lines changed: 3 additions & 175 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
[![Build Status]](https://github.com/lcobucci/jwt/actions?query=workflow%3A%22PHPUnit%20Tests%22+branch%3A3.4)
88
[![Code Coverage]](https://codecov.io/gh/lcobucci/jwt)
99

10-
A simple library to work with JSON Web Token and JSON Web Signature (requires PHP 5.6+).
11-
The implementation is based on the [RFC 7519](https://tools.ietf.org/html/rfc7519).
10+
A simple library to work with JSON Web Token and JSON Web Signature based on the [RFC 7519](https://tools.ietf.org/html/rfc7519).
1211

1312
## Installation
1413

@@ -19,180 +18,9 @@ you can install it using [Composer](http://getcomposer.org).
1918
composer require lcobucci/jwt
2019
```
2120

22-
### Dependencies
21+
## Documentation
2322

24-
- PHP 5.6+
25-
- OpenSSL Extension
26-
27-
## Basic usage
28-
29-
### Creating
30-
31-
Just use the builder to create a new JWT/JWS tokens:
32-
33-
```php
34-
use Lcobucci\JWT\Builder;
35-
36-
$time = time();
37-
$token = (new Builder())->issuedBy('http://example.com') // Configures the issuer (iss claim)
38-
->permittedFor('http://example.org') // Configures the audience (aud claim)
39-
->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
40-
->issuedAt($time) // Configures the time that the token was issue (iat claim)
41-
->canOnlyBeUsedAfter($time + 60) // Configures the time that the token can be used (nbf claim)
42-
->expiresAt($time + 3600) // Configures the expiration time of the token (exp claim)
43-
->withClaim('uid', 1) // Configures a new claim, called "uid"
44-
->getToken(); // Retrieves the generated token
45-
46-
47-
$token->getHeaders(); // Retrieves the token headers
48-
$token->getClaims(); // Retrieves the token claims
49-
50-
echo $token->getHeader('jti'); // will print "4f1g23a12aa"
51-
echo $token->getClaim('iss'); // will print "http://example.com"
52-
echo $token->getClaim('uid'); // will print "1"
53-
echo $token; // The string representation of the object is a JWT string (pretty easy, right?)
54-
```
55-
56-
### Parsing from strings
57-
58-
Use the parser to create a new token from a JWT string (using the previous token as example):
59-
60-
```php
61-
use Lcobucci\JWT\Parser;
62-
63-
$token = (new Parser())->parse((string) $token); // Parses from a string
64-
$token->getHeaders(); // Retrieves the token header
65-
$token->getClaims(); // Retrieves the token claims
66-
67-
echo $token->getHeader('jti'); // will print "4f1g23a12aa"
68-
echo $token->getClaim('iss'); // will print "http://example.com"
69-
echo $token->getClaim('uid'); // will print "1"
70-
```
71-
72-
### Validating
73-
74-
We can easily validate if the token is valid (using the previous token and time as example):
75-
76-
```php
77-
use Lcobucci\JWT\ValidationData;
78-
79-
$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
80-
$data->setIssuer('http://example.com');
81-
$data->setAudience('http://example.org');
82-
$data->setId('4f1g23a12aa');
83-
84-
var_dump($token->validate($data)); // false, because token cannot be used before now() + 60
85-
86-
$data->setCurrentTime($time + 61); // changing the validation time to future
87-
88-
var_dump($token->validate($data)); // true, because current time is between "nbf" and "exp" claims
89-
90-
$data->setCurrentTime($time + 4000); // changing the validation time to future
91-
92-
var_dump($token->validate($data)); // false, because token is expired since current time is greater than exp
93-
94-
// We can also use the $leeway parameter to deal with clock skew (see notes below)
95-
// If token's claimed time is invalid but the difference between that and the validation time is less than $leeway,
96-
// then token is still considered valid
97-
$dataWithLeeway = new ValidationData($time, 20);
98-
$dataWithLeeway->setIssuer('http://example.com');
99-
$dataWithLeeway->setAudience('http://example.org');
100-
$dataWithLeeway->setId('4f1g23a12aa');
101-
102-
var_dump($token->validate($dataWithLeeway)); // false, because token can't be used before now() + 60, not within leeway
103-
104-
$dataWithLeeway->setCurrentTime($time + 51); // changing the validation time to future
105-
106-
var_dump($token->validate($dataWithLeeway)); // true, because current time plus leeway is between "nbf" and "exp" claims
107-
108-
$dataWithLeeway->setCurrentTime($time + 3610); // changing the validation time to future but within leeway
109-
110-
var_dump($token->validate($dataWithLeeway)); // true, because current time - 20 seconds leeway is less than exp
111-
112-
$dataWithLeeway->setCurrentTime($time + 4000); // changing the validation time to future outside of leeway
113-
114-
var_dump($token->validate($dataWithLeeway)); // false, because token is expired since current time is greater than exp
115-
```
116-
117-
#### Important
118-
119-
- You have to configure ```ValidationData``` informing all claims you want to validate the token.
120-
- If ```ValidationData``` contains claims that are not being used in token or token has claims that are not
121-
configured in ```ValidationData``` they will be ignored by ```Token::validate()```.
122-
- ```exp```, ```nbf``` and ```iat``` claims are configured by default in ```ValidationData::__construct()```
123-
with the current UNIX time (```time()```).
124-
- The optional ```$leeway``` parameter of ```ValidationData``` will cause us to use that number of seconds of leeway
125-
when validating the time-based claims, pretending we are further in the future for the "Issued At" (```iat```) and "Not
126-
Before" (```nbf```) claims and pretending we are further in the past for the "Expiration Time" (```exp```) claim. This
127-
allows for situations where the clock of the issuing server has a different time than the clock of the verifying server,
128-
as mentioned in [section 4.1 of RFC 7519](https://tools.ietf.org/html/rfc7519#section-4.1).
129-
130-
## Token signature
131-
132-
We can use signatures to be able to verify if the token was not modified after its generation. This library implements Hmac, RSA and ECDSA signatures (using 256, 384 and 512).
133-
134-
### Important
135-
136-
Do not allow the string sent to the Parser to dictate which signature algorithm
137-
to use, or else your application will be vulnerable to a [critical JWT security vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries).
138-
139-
The examples below are safe because the choice in `Signer` is hard-coded and
140-
cannot be influenced by malicious users.
141-
142-
### Hmac
143-
144-
Hmac signatures are really simple to be used:
145-
146-
```php
147-
use Lcobucci\JWT\Builder;
148-
use Lcobucci\JWT\Signer\Key;
149-
use Lcobucci\JWT\Signer\Hmac\Sha256;
150-
151-
$signer = new Sha256();
152-
$time = time();
153-
154-
$token = (new Builder())->issuedBy('http://example.com') // Configures the issuer (iss claim)
155-
->permittedFor('http://example.org') // Configures the audience (aud claim)
156-
->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
157-
->issuedAt($time) // Configures the time that the token was issue (iat claim)
158-
->canOnlyBeUsedAfter($time + 60) // Configures the time that the token can be used (nbf claim)
159-
->expiresAt($time + 3600) // Configures the expiration time of the token (exp claim)
160-
->withClaim('uid', 1) // Configures a new claim, called "uid"
161-
->getToken($signer, new Key('testing')); // Retrieves the generated token
162-
163-
164-
var_dump($token->verify($signer, 'testing 1')); // false, because the key is different
165-
var_dump($token->verify($signer, 'testing')); // true, because the key is the same
166-
```
167-
168-
### RSA and ECDSA
169-
170-
RSA and ECDSA signatures are based on public and private keys so you have to generate using the private key and verify using the public key:
171-
172-
```php
173-
use Lcobucci\JWT\Builder;
174-
use Lcobucci\JWT\Signer\Key;
175-
use Lcobucci\JWT\Signer\Rsa\Sha256; // you can use Lcobucci\JWT\Signer\Ecdsa\Sha256 if you're using ECDSA keys
176-
177-
$signer = new Sha256();
178-
$privateKey = new Key('file://{path to your private key}');
179-
$time = time();
180-
181-
$token = (new Builder())->issuedBy('http://example.com') // Configures the issuer (iss claim)
182-
->permittedFor('http://example.org') // Configures the audience (aud claim)
183-
->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
184-
->issuedAt($time) // Configures the time that the token was issue (iat claim)
185-
->canOnlyBeUsedAfter($time + 60) // Configures the time that the token can be used (nbf claim)
186-
->expiresAt($time + 3600) // Configures the expiration time of the token (exp claim)
187-
->withClaim('uid', 1) // Configures a new claim, called "uid"
188-
->getToken($signer, $privateKey); // Retrieves the generated token
189-
190-
$publicKey = new Key('file://{path to your public key}');
191-
192-
var_dump($token->verify($signer, $publicKey)); // true when the public key was generated by the private one =)
193-
```
194-
195-
**It's important to say that if you're using RSA keys you shouldn't invoke ECDSA signers (and vice-versa), otherwise ```sign()``` and ```verify()``` will raise an exception!**
23+
The documentation is available at <https://lcobucci-jwt.readthedocs.io/en/3.4.0/>.
19624

19725
[Gitter]: https://img.shields.io/badge/GITTER-JOIN%20CHAT%20%E2%86%92-brightgreen.svg?style=flat-square
19826
[Total Downloads]: https://img.shields.io/packagist/dt/lcobucci/jwt.svg?style=flat-square

docs/configuration.md

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# Configuration
2+
3+
In order to simplify the setup of the library, we provide the class `Lcobucci\JWT\Configuration`.
4+
5+
It's meant for:
6+
7+
* Configuring the default algorithm (signer) and key(s) to be used
8+
* Configuring the default set of validation constraints
9+
* Providing custom implementation for the [extension points](extending-the-library.md)
10+
* Retrieving components (encoder, decoder, parser, validator, and builder)
11+
12+
## Usage
13+
14+
In order to use it, you must:
15+
16+
1. Initialise the configuration object
17+
1. Customise the configuration object
18+
1. Retrieve components
19+
20+
### Configuration initialisation
21+
22+
The `Lcobucci\JWT\Signer\Key` object is used for symmetric/asymmetric signature.
23+
24+
To initialise it, you can pass the key content as a plain text:
25+
26+
```php
27+
use Lcobucci\JWT\Signer\Key\InMemory;
28+
29+
$key = InMemory::plainText('my-key-as-plaintext');
30+
```
31+
32+
Provide a base64 encoded string:
33+
34+
```php
35+
use Lcobucci\JWT\Signer\Key\InMemory;
36+
37+
$key = InMemory::base64Encoded('YSB2ZXJ5IGxvbmcgYSB2ZXJ5IHVsdHJhIHNlY3VyZSBrZXkgZm9yIG15IGFtYXppbmcgdG9rZW5z');
38+
```
39+
40+
Or provide a file path:
41+
42+
```php
43+
use Lcobucci\JWT\Signer\Key\InMemory;
44+
use Lcobucci\JWT\Signer\Key\LocalFileReference;
45+
46+
$key = InMemory::file(__DIR__ . '/path-to-my-key-stored-in-a-file.pem'); // this reads the file and keeps its contents in memory
47+
$key = LocalFileReference::file(__DIR__ . '/path-to-my-key-stored-in-a-file.pem'); // this just keeps a reference to file
48+
```
49+
50+
#### For symmetric algorithms
51+
52+
Symmetric algorithms use the same key for both signature creation and verification.
53+
This means that it's really important that your key **remains secret**.
54+
55+
!!! Tip
56+
It is recommended that you use a key with lots of entropy, preferably generated using a cryptographically secure pseudo-random number generator (CSPRNG).
57+
You can use the [CryptoKey](https://github.com/AndrewCarterUK/CryptoKey) tool to do this for you.
58+
59+
```php
60+
use Lcobucci\JWT\Configuration;
61+
use Lcobucci\JWT\Signer\Hmac\Sha256;
62+
use Lcobucci\JWT\Signer\Key\InMemory;
63+
64+
$configuration = Configuration::forSymmetricSigner(
65+
// You may use any HMAC variations (256, 384, and 512)
66+
new Sha256(),
67+
// replace the value below with a key of your own!
68+
InMemory::base64Encoded('mBC5v1sOKVvbdEitdSBenu59nfNfhwkedkJVNabosTw=')
69+
// You may also override the JOSE encoder/decoder if needed by providing extra arguments here
70+
);
71+
```
72+
73+
#### For asymmetric algorithms
74+
75+
Asymmetric algorithms use a **private key** for signature creation and a **public key** for verification.
76+
This means that it's fine to distribute your **public key**. However, the **private key** should **remain secret**.
77+
78+
```php
79+
use Lcobucci\JWT\Configuration;
80+
use Lcobucci\JWT\Signer;
81+
use Lcobucci\JWT\Signer\Key\LocalFileReference;
82+
use Lcobucci\JWT\Signer\Key\InMemory;
83+
84+
$configuration = Configuration::forAsymmetricSigner(
85+
// You may use RSA or ECDSA and all their variations (256, 384, and 512)
86+
new Signer\RSA\Sha256(),
87+
LocalFileReference::file(__DIR__ . '/my-private-key.pem'),
88+
InMemory::base64Encoded('mBC5v1sOKVvbdEitdSBenu59nfNfhwkedkJVNabosTw=')
89+
// You may also override the JOSE encoder/decoder if needed by providing extra arguments here
90+
);
91+
```
92+
93+
#### For no algorithm
94+
95+
!!! Warning
96+
This configuration type is **NOT** recommended for production environments.
97+
It's only provided to allow people to have a simpler and faster setup for tests, avoiding any kind of signature creation/verification.
98+
99+
```php
100+
use Lcobucci\JWT\Configuration;
101+
102+
$configuration = Configuration::forUnsecuredSigner(
103+
// You may also override the JOSE encoder/decoder if needed by providing extra arguments here
104+
);
105+
```
106+
107+
### Customisation
108+
109+
By using the setters of the `Lcobucci\JWT\Configuration` you may customise the setup of this library.
110+
111+
!!! Important
112+
If you want to use a customised configuration, please make sure you call the setters before of invoking any getter.
113+
Otherwise, the default implementations will be used.
114+
115+
These are the available setters:
116+
117+
* `Lcobucci\JWT\Configuration#setBuilderFactory()`: configures how the token builder should be created
118+
* `Lcobucci\JWT\Configuration#setParser()`: configures a custom token parser
119+
* `Lcobucci\JWT\Configuration#setValidator()`: configures a custom validator
120+
* `Lcobucci\JWT\Configuration#setValidationConstraints()`: configures the default set of validation constraints
121+
122+
### Retrieve components
123+
124+
Once you've made all the necessary configuration you can pass the configuration object around your code and use the getters to retrieve the components:
125+
126+
These are the available getters:
127+
128+
* `Lcobucci\JWT\Configuration#builder()`: retrieves the token builder (always creating a new instance)
129+
* `Lcobucci\JWT\Configuration#parser()`: retrieves the token parser
130+
* `Lcobucci\JWT\Configuration#signer()`: retrieves the signer
131+
* `Lcobucci\JWT\Configuration#signingKey()`: retrieves the key for signature creation
132+
* `Lcobucci\JWT\Configuration#verificationKey()`: retrieves the key for signature verification
133+
* `Lcobucci\JWT\Configuration#validator()`: retrieves the token validator
134+
* `Lcobucci\JWT\Configuration#validationConstraints()`: retrieves the default set of validation constraints

docs/index.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Overview
2+
3+
`lcobucci/jwt` is a framework-agnostic PHP library that allows you to issue, parse, and validate JSON Web Tokens based on the [RFC 7519].
4+
5+
## Support
6+
7+
If you're having any issue to use the library, please [create a GH issue].
8+
You can also reach us and other users of this library via our [Gitter channel].
9+
10+
## License
11+
12+
The project is licensed under the MIT license, see [LICENSE file].
13+
14+
[RFC 7519]: https://tools.ietf.org/html/rfc7519
15+
[create a GH issue]: https://github.com/lcobucci/jwt/issues/new
16+
[Gitter channel]: https://gitter.im/lcobucci/jwt
17+
[LICENSE file]: https://github.com/lcobucci/jwt/blob/master/LICENSE

docs/installation.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Installation
2+
3+
This package is available on [Packagist] and you can install it using [Composer].
4+
5+
By running the following command you'll add `lcobucci/jwt` as a dependency to your project:
6+
7+
```sh
8+
composer require lcobucci/jwt
9+
```
10+
11+
## Autoloading
12+
13+
!!! Note
14+
We'll be omitting the autoloader from the code samples to simplify the documentation.
15+
16+
In order to be able to use the classes provided by this library you're also required to include [Composer]'s autoloader in your application:
17+
18+
```php
19+
require 'vendor/bin/autoload.php';
20+
```
21+
22+
!!! Tip
23+
If you're not familiar with how [composer] works, we highly recommend you to take some time to read it's documentation - especially the [autoloading section].
24+
25+
[Packagist]: https://packagist.org/packages/lcobucci/jwt
26+
[Composer]: https://getcomposer.org
27+
[autoloading section]: https://getcomposer.org/doc/01-basic-usage.md#autoloading

0 commit comments

Comments
 (0)