Passed
Push — master ( 904589...078d26 )
by Thomas Mauro
02:52
created

PrivateKeyJwt::createAuthJwt()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 3.0008

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 35
ccs 21
cts 22
cp 0.9545
rs 9.584
c 0
b 0
f 0
cc 3
nc 2
nop 2
crap 3.0008
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\OpenIdClient\AuthMethod;
6
7
use Jose\Component\Signature\JWSBuilder;
8
use Jose\Component\Signature\Serializer\Serializer;
9
use TMV\OpenIdClient\ClientInterface as OpenIDClient;
10
use TMV\OpenIdClient\Exception\RuntimeException;
11
12
final class PrivateKeyJwt extends AbstractJwtAuth
13
{
14
    /** @var JWSBuilder */
15
    private $jwsBuilder;
16
17
    /** @var Serializer */
18
    private $jwsSerializer;
19
20
    /** @var null|string */
21
    private $kid;
22
23
    /** @var int */
24
    private $tokenTTL;
25
26
    /**
27
     * PrivateKeyJwt constructor.
28
     *
29
     * @param JWSBuilder $jwsBuilder
30
     * @param Serializer $serializer
31
     * @param string|null $kid
32
     * @param int $tokenTTL
33
     */
34 2
    public function __construct(
35
        JWSBuilder $jwsBuilder,
36
        Serializer $serializer,
37
        ?string $kid = null,
38
        int $tokenTTL = 60
39
    ) {
40 2
        $this->jwsBuilder = $jwsBuilder;
41 2
        $this->jwsSerializer = $serializer;
42 2
        $this->kid = $kid;
43 2
        $this->tokenTTL = $tokenTTL;
44 2
    }
45
46 1
    public function getSupportedMethod(): string
47
    {
48 1
        return 'private_key_jwt';
49
    }
50
51 1
    protected function createAuthJwt(OpenIDClient $client, array $claims = []): string
52
    {
53 1
        $issuer = $client->getIssuer();
54 1
        $issuerMetadata = $issuer->getMetadata();
55
56 1
        $clientId = $client->getMetadata()->getClientId();
57
58 1
        $jwk = $client->getJWKS()->selectKey('sig', null, $this->kid ? ['kid' => $this->kid] : []);
59
60 1
        if (! $jwk) {
61
            throw new RuntimeException('Unable to get a client signature jwk');
62
        }
63
64 1
        $time = \time();
65 1
        $jti = \bin2hex(\random_bytes(32));
66
67
        /** @var string $payload */
68 1
        $payload = \json_encode(\array_merge(
69 1
            $claims,
70
            [
71 1
                'iss' => $clientId,
72 1
                'sub' => $clientId,
73 1
                'aud' => $issuerMetadata->getIssuer(),
74 1
                'iat' => $time,
75 1
                'exp' => $time + $this->tokenTTL,
76 1
                'jti' => $jti,
77
            ]
78
        ));
79
80 1
        $jws = $this->jwsBuilder->create()
81 1
            ->withPayload($payload)
82 1
            ->addSignature($jwk, ['alg' => $jwk->get('alg'), 'jti' => $jti])
83 1
            ->build();
84
85 1
        return $this->jwsSerializer->serialize($jws, 0);
86
    }
87
}
88