JWTListener::handle()   B
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 26
rs 8.5806
cc 4
eloc 14
nc 4
nop 1
1
<?php
2
3
namespace ApiBundle\Security\Firewall;
4
5
use ApiBundle\Security\Authentication\Token\JWTUserToken;
6
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
7
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
8
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
9
use Symfony\Component\Security\Core\Exception\AuthenticationException;
10
use Symfony\Component\Security\Http\Firewall\ListenerInterface;
11
12
class JWTListener implements ListenerInterface
13
{
14
    const HEADER_PREFIX = 'Bearer';
15
16
    /**
17
     * @var TokenStorageInterface
18
     */
19
    protected $tokenStorage;
20
21
    /**
22
     * @var AuthenticationManagerInterface
23
     */
24
    protected $authenticationManager;
25
26
    /**
27
     * @param SecurityContextInterface|TokenStorageInterface $tokenStorage
28
     * @param AuthenticationManagerInterface                 $authenticationManager
29
     */
30
    public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager)
31
    {
32
        $this->tokenStorage = $tokenStorage;
33
        $this->authenticationManager = $authenticationManager;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function handle(GetResponseEvent $event)
40
    {
41
        $request = $event->getRequest();
42
        // note, if you want to allow token from query parameters or cookie, act accordingly
43
        if (!$request->headers->has('Authorization')) {
44
            throw new AuthenticationException("Authorization header is missing");
45
        }
46
47
        // extract parts from authorization header: prefix - jwt
48
        $parts = explode(' ', $request->headers->get('Authorization'));
49
        if (count($parts) !== 2) {
50
            throw new AuthenticationException("Authorization header is not valid");
51
        }
52
53
        // match authorization header prefix
54
        list($prefix, $jwt) = $parts;
55
        if (self::HEADER_PREFIX !== $prefix) {
56
            throw new AuthenticationException("Authorization header prefix is not valid");
57
        }
58
59
        $token = new JWTUserToken();
60
        $token->setRawToken($jwt);
61
62
        $authToken = $this->authenticationManager->authenticate($token);
63
        $this->tokenStorage->setToken($authToken);
64
    }
65
}
66