Passed
Push — feature/add-jwt-signature-gene... ( b66566 )
by Vitaliy
05:23
created

WebTokenJwtSignatureGenerator::generate()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 16
nc 1
nop 1
1
<?php
2
3
declare(strict_types = 1);
4
5
/*
6
 * This file is part of the AppleApnPush package
7
 *
8
 * (c) Vitaliy Zhuk <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code
12
 */
13
14
namespace Apple\ApnPush\Jwt\SignatureGenerator;
15
16
use Apple\ApnPush\Jwt\JwtInterface;
17
use Jose\Component\Core\AlgorithmManager;
18
use Jose\Component\Core\Converter\JsonConverter;
19
use Jose\Component\Core\Converter\StandardConverter;
20
use Jose\Component\KeyManagement\JWKFactory;
21
use Jose\Component\Signature\Algorithm\ES256;
22
use Jose\Component\Signature\JWSBuilder;
23
use Jose\Component\Signature\Serializer\CompactSerializer;
24
use Jose\Component\Signature\Serializer\JWSSerializer;
25
26
/**
27
 * The JWT signature generator worked with "web-token/jwt-*" libraries.
28
 *
29
 * Next libraries must be installed:
30
 *      - web-token/jwt-key-mgmt
31
 *      - web-token/jwt-core
32
 *      - web-token/jwt-signature
33
 */
34
class WebTokenJwtSignatureGenerator implements SignatureGeneratorInterface
35
{
36
    /**
37
     * @var JsonConverter
38
     */
39
    private $jsonConverter;
40
41
    /**
42
     * @var JWSBuilder
43
     */
44
    private $jwsBuilder;
45
46
    /**
47
     * @var JWSSerializer
48
     */
49
    private $serializer;
50
51
    /**
52
     * Constructor.
53
     */
54
    public function __construct()
55
    {
56
        $this->jsonConverter = new StandardConverter();
57
        $this->jwsBuilder = new JWSBuilder($this->jsonConverter, AlgorithmManager::create([new ES256()]));
58
        $this->serializer = new CompactSerializer($this->jsonConverter);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function generate(JwtInterface $jwt): string
65
    {
66
        $jwk = JWKFactory::createFromKeyFile($jwt->getPath(), '', [
67
            'kid' => $jwt->getKey(),
68
        ]);
69
70
        $claims = [
71
            'iss' => $jwt->getTeamId(),
72
            'iat' => time(),
73
        ];
74
75
        $header = [
76
            'alg' => 'ES256',
77
            'kid' => $jwk->get('kid'),
78
        ];
79
80
        $payload = $this->jsonConverter->encode($claims);
81
82
        $jws = $this->jwsBuilder
83
            ->create()
84
            ->withPayload($payload)
85
            ->addSignature($jwk, $header)
86
            ->build();
87
88
        return $this->serializer->serialize($jws);
89
    }
90
}
91