Passed
Branch master (a006bc)
by Vitaliy
05:17 queued 02:53
created

JwtAuthenticator   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 5
dl 0
loc 61
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A authenticate() 0 8 1
B createJwsContent() 0 24 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\Protocol\Http\Authenticator;
15
16
use Apple\ApnPush\Jwt\JwtInterface;
17
use Apple\ApnPush\Protocol\Http\Request;
18
use Jose\Factory\JWKFactory;
19
use Jose\Factory\JWSFactory;
20
21
/**
22
 * Authenticate request via Json Web Token
23
 */
24
class JwtAuthenticator implements AuthenticatorInterface
25
{
26
    private const ALGORITHM = 'ES256';
27
28
    /**
29
     * @var JwtInterface
30
     */
31
    private $jwt;
32
33
    /**
34
     * Constructor.
35
     *
36
     * @param JwtInterface $jwt
37
     */
38
    public function __construct(JwtInterface $jwt)
39
    {
40
        $this->jwt = $jwt;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function authenticate(Request $request): Request
47
    {
48
        $jws = $this->createJwsContent();
49
50
        $request = $request->withHeader('authorization', sprintf('bearer %s', $jws));
51
52
        return $request;
53
    }
54
55
    /**
56
     * Create the content of JWS by Json Web Token
57
     *
58
     * @return string
59
     */
60
    private function createJwsContent(): string
61
    {
62
        $jwk = JWKFactory::createFromKeyFile($this->jwt->getPath(), '', [
63
            'kid' => $this->jwt->getKey(),
64
            'alg' => self::ALGORITHM,
65
            'use' => 'sig',
66
        ]);
67
68
        $payload = [
69
            'iss' => $this->jwt->getTeamId(),
70
            'iat' => time(),
71
        ];
72
73
        $header = [
74
            'alg' => self::ALGORITHM,
75
            'kid' => $jwk->get('kid'),
76
        ];
77
78
        return JWSFactory::createJWSToCompactJSON(
79
            $payload,
80
            $jwk,
81
            $header
82
        );
83
    }
84
}
85