1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
/* |
3
|
|
|
* This file is part of the KleijnWeb\JwtBundle package. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace KleijnWeb\JwtBundle\Firewall; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @author John Kleijn <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
use KleijnWeb\JwtBundle\Authentication\JwtAuthenticationToken; |
15
|
|
|
use Symfony\Component\HttpFoundation\Request; |
16
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseEvent; |
17
|
|
|
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; |
18
|
|
|
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
19
|
|
|
use Symfony\Component\Security\Http\Firewall\ListenerInterface; |
20
|
|
|
|
21
|
|
|
class JwtAuthenticationListener implements ListenerInterface |
22
|
|
|
{ |
23
|
|
|
const HEADER_AUTH = 'Authorization'; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var TokenStorageInterface |
27
|
|
|
*/ |
28
|
|
|
protected $tokenStorage; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var AuthenticationManagerInterface |
32
|
|
|
*/ |
33
|
|
|
protected $authenticationManager; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var string |
37
|
|
|
*/ |
38
|
|
|
private $header; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param TokenStorageInterface $tokenStorage |
42
|
|
|
* @param AuthenticationManagerInterface $authenticationManager |
43
|
|
|
* @param string $header |
44
|
|
|
*/ |
45
|
|
|
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, string $header = self::HEADER_AUTH) |
46
|
|
|
{ |
47
|
|
|
$this->tokenStorage = $tokenStorage; |
48
|
|
|
$this->authenticationManager = $authenticationManager; |
49
|
|
|
$this->header = $header; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param GetResponseEvent $event |
54
|
|
|
*/ |
55
|
|
|
public function handle(GetResponseEvent $event) |
56
|
|
|
{ |
57
|
|
|
if (!$token = $this->createToken($event->getRequest())) { |
58
|
|
|
return; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$this->tokenStorage->setToken($this->authenticationManager->authenticate($token)); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @param Request $request |
66
|
|
|
* |
67
|
|
|
* @return JwtAuthenticationToken|null |
68
|
|
|
*/ |
69
|
|
|
public function createToken(Request $request) |
70
|
|
|
{ |
71
|
|
|
$tokenString = $request->headers->get($this->header); |
72
|
|
|
|
73
|
|
|
if ($this->header == self::HEADER_AUTH && 0 === strpos((string)$tokenString, 'Bearer ')) { |
74
|
|
|
$tokenString = substr($tokenString, 7); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
if (!$tokenString) { |
78
|
|
|
return null; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return new JwtAuthenticationToken([], $tokenString); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|