1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bludata\Lumen\Authentication\JWT\Libs; |
4
|
|
|
|
5
|
|
|
use Bludata\Lumen\Authentication\JWT\Interfaces\JWTInterface; |
6
|
|
|
use Exception; |
7
|
|
|
use Lcobucci\JWT\Builder; |
8
|
|
|
use Lcobucci\JWT\Parser; |
9
|
|
|
use Lcobucci\JWT\Signer\Hmac\Sha256; |
10
|
|
|
use Lcobucci\JWT\Token; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Basic gadget for using of the JWT. |
14
|
|
|
* |
15
|
|
|
* @author Cristian B. dos Santos <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class JWT implements JWTInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* The builder token. |
21
|
|
|
* |
22
|
|
|
* @var Lcobucci\JWT\Builder |
23
|
|
|
*/ |
24
|
|
|
protected $builder; |
25
|
|
|
|
26
|
|
|
public function __construct() |
27
|
|
|
{ |
28
|
|
|
$this->builder = new Builder(); |
|
|
|
|
29
|
|
|
|
30
|
|
|
$this->builder |
31
|
|
|
->setIssuer(gethostname()) |
32
|
|
|
->setId(time(), true); |
33
|
|
|
// ->setIssuedAt(time()) |
|
|
|
|
34
|
|
|
// ->setNotBefore(time() + 60) |
|
|
|
|
35
|
|
|
// ->setExpiration(time() + 3600) |
|
|
|
|
36
|
|
|
// ->set('teste', 1); |
|
|
|
|
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Create object of a token. |
41
|
|
|
* |
42
|
|
|
* @param array $user |
43
|
|
|
* |
44
|
|
|
* @return Lcobucci\JWT\Token |
45
|
|
|
*/ |
46
|
|
|
public function generateTokenByUser($user) |
47
|
|
|
{ |
48
|
|
|
return $this->builder |
49
|
|
|
->set('user', $user) |
50
|
|
|
->sign(new Sha256(), env('JWT_SECRET')) |
51
|
|
|
->getToken(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* [Return the value of a token the request]. |
56
|
|
|
* |
57
|
|
|
* @param string $token |
58
|
|
|
* |
59
|
|
|
* @return Lcobucci\JWT\Token |
|
|
|
|
60
|
|
|
*/ |
61
|
|
|
public function decodeToken($token) |
62
|
|
|
{ |
63
|
|
|
try { |
64
|
|
|
$parser = new Parser(); |
65
|
|
|
|
66
|
|
|
if (!$token = $parser->parse((string) $token)) { |
|
|
|
|
67
|
|
|
throw new Exception('Token inválido'); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $token; |
|
|
|
|
71
|
|
|
} catch (Exception $e) { |
72
|
|
|
abort(401, 'Favor efetuar o login novamente'); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Verify is validate token in signature. |
78
|
|
|
* |
79
|
|
|
* @param Lcobucci\JWT\Token $token |
|
|
|
|
80
|
|
|
* |
81
|
|
|
* @return bool |
82
|
|
|
*/ |
83
|
|
|
public function isValidByToken(Token $token) |
84
|
|
|
{ |
85
|
|
|
return $token->verify(new Sha256(), env('JWT_SECRET')); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..