JWT Framework
Search…
JWS Creation
Now that you have an algorithm manager and a key, it is time to create your first signed token.
The computation is done by the JWSBuilder object. This object only requires the algorithm manager.
1
<?php
2
3
use Jose\Component\Core\AlgorithmManager;
4
use Jose\Component\Core\JWK;
5
use Jose\Component\Signature\Algorithm\HS256;
6
use Jose\Component\Signature\JWSBuilder;
7
8
// The algorithm manager with the HS256 algorithm.
9
$algorithmManager = new AlgorithmManager([
10
new HS256(),
11
]);
12
13
// Our key.
14
$jwk = new JWK([
15
'kty' => 'oct',
16
'k' => 'dzI6nbW4OcNF-AtfxGAmuyz7IpHRudBI0WgGjZWgaRJt6prBn3DARXgUR8NVwKhfL43QBIU2Un3AvCGCHRgY4TbEqhOi8-i98xxmCggNjde4oaW6wkJ2NgM3Ss9SOX9zS3lcVzdCMdum-RwVJ301kbin4UtGztuzJBeg5oVN00MGxjC2xWwyI0tgXVs-zJs5WlafCuGfX1HrVkIf5bvpE0MQCSjdJpSeVao6-RSTYDajZf7T88a2eVjeW31mMAg-jzAWfUrii61T_bYPJFOXW8kkRWoa1InLRdG6bKB9wQs9-VdXZP60Q4Yuj_WZ-lO7qV9AEFrUkkjpaDgZT86w2g',
17
]);
18
19
// We instantiate our JWS Builder.
20
$jwsBuilder = new JWSBuilder($algorithmManager);
Copied!
Now let's create our first JWS object.
1
// The payload we want to sign. The payload MUST be a string hence we use our JSON Converter.
2
$payload = json_encode([
3
'iat' => time(),
4
'nbf' => time(),
5
'exp' => time() + 3600,
6
'iss' => 'My service',
7
'aud' => 'Your application',
8
]);
9
10
$jws = $jwsBuilder
11
->create() // We want to create a new JWS
12
->withPayload($payload) // We set the payload
13
->addSignature($jwk, ['alg' => 'HS256']) // We add a signature with a simple protected header
14
->build(); // We build it
Copied!
Great! If everything is fine you will get a JWS object with one signature. We want to send it to the audience. Before that, it must be serialized.
We will use the compact serialization mode. This is the most common mode as it is URL safe and very compact. Perfect for a use in a web context!
1
use Jose\Component\Signature\Serializer\CompactSerializer;
2
3
$serializer = new CompactSerializer(); // The serializer
4
5
$token = $serializer->serialize($jws, 0); // We serialize the signature at index 0 (we only have one signature).
Copied!
All good! The variable $token now contains a string that should be something like this:
1
eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MDc4OTY5OTIsIm5iZiI6MTUwNzg5Njk5MiwiZXhwIjoxNTA3OTAwNTkyLCJpc3MiOiJNeSBzZXJ2aWNlIiwiYXVkIjoiWW91ciBhcHBsaWNhdGlvbiJ9.eycp9PTdgO4WA-68-AMoHPwsKDr68NhjIQKz4lUkiI0
Copied!
Other serialization modes exist. We will see them in the Advanced Topics section.
Last modified 2yr ago
Copy link