Completed
Push — master ( afb42c...661861 )
by Joao
09:18
created

JwtWrapper::extractData()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
c 0
b 0
f 0
rs 9.6
cc 4
nc 4
nop 1
1
<?php
2
3
namespace ByJG\Util;
4
5
use Firebase\JWT\JWT;
6
7
class JwtWrapper
8
{
9
10
    protected $serverName;
11
12
    /**
13
     * @var JwtKeyInterface
14
     */
15
    protected $jwtKey;
16
17
    /**
18
     * JwtWrapper constructor.
19
     * @param string $serverName
20
     * @param JwtKeyInterface $jwtKey
21
     * @throws JwtWrapperException
22
     */
23
    public function __construct($serverName, $jwtKey)
24
    {
25
        $this->serverName = $serverName;
26
        $this->jwtKey = $jwtKey;
27
28
        if (!($jwtKey instanceof JwtKeyInterface)) {
29
            throw new JwtWrapperException('Constructor needs to receive a JwtKeyInterface');
30
        }
31
    }
32
33
    /**
34
     * @param $data
35
     * @param int $secondsExpire In Seconds
36
     * @param int $secondsNotBefore In Seconds
37
     * @return array
38
     */
39
    public function createJwtData($data, $secondsExpire = 60, $secondsNotBefore = 0)
40
    {
41
        $tokenId    = base64_encode(openssl_random_pseudo_bytes(32));
42
        $issuedAt   = time();
43
        $notBefore  = $issuedAt + $secondsNotBefore;          //Adding 10 seconds
44
        $expire     = $notBefore + $secondsExpire;            // Adding 60 seconds
45
        $serverName = $this->serverName;                       // Retrieve the server name from config file
46
47
        /*
48
         * Create the token as an array
49
         */
50
        return [
51
            'iat'  => $issuedAt,         // Issued at: time when the token was generated
52
            'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
53
            'iss'  => $serverName,       // Issuer
54
            'nbf'  => $notBefore,        // Not before
55
            'exp'  => $expire,           // Expire
56
            'data' => $data              // Data related to the signer user
57
        ];
58
    }
59
60
    public function generateToken($jwtData)
61
    {
62
        /*
63
         * Encode the array to a JWT string.
64
         * Second parameter is the key to encode the token.
65
         *
66
         * The output string can be validated at http://jwt.io/
67
         */
68
        $jwt = JWT::encode(
69
            $jwtData,      //Data to be encoded in the JWT
70
            $this->jwtKey->getPrivateKey(), // The signing key
71
            $this->jwtKey->getAlghoritm()
72
        );
73
74
        return $jwt;
75
    }
76
77
    /**
78
     * Extract the key, which is coming from the config file.
79
     *
80
     * Best suggestion is the key to be a binary string and
81
     * store it in encoded in a config file.
82
     *
83
     * Can be generated with base64_encode(openssl_random_pseudo_bytes(64));
84
     *
85
     * keep it secure! You'll need the exact key to verify the
86
     * token later.
87
     *
88
     * @param null $bearer
89
     * @return object
90
     * @throws JwtWrapperException
91
     */
92
    public function extractData($bearer = null)
93
    {
94
        if (empty($bearer)) {
95
            $bearer = $this->getAuthorizationBearer();
96
        }
97
98
        $jwtData = JWT::decode(
99
            $bearer,
100
            $this->jwtKey->getPublicKey(),
101
            [
102
                $this->jwtKey->getAlghoritm()
103
            ]
104
        );
105
106
        if (isset($jwtData->iss) && $jwtData->iss != $this->serverName) {
107
            throw new JwtWrapperException("Issuer does not match");
108
        }
109
110
        return $jwtData;
111
    }
112
113
    /**
114
     * @return mixed
115
     * @throws JwtWrapperException
116
     */
117
    public function getAuthorizationBearer()
118
    {
119
        $authorization = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
120
        list($bearer) = sscanf($authorization, 'Bearer %s');
121
122
        if (empty($bearer)) {
123
            throw new JwtWrapperException('Absent authorization token');
124
        }
125
126
        return $bearer;
127
    }
128
129
    public static function generateSecret($bytes)
130
    {
131
        return base64_encode(openssl_random_pseudo_bytes($bytes));
132
    }
133
}