Completed
Pull Request — master (#15)
by Oguzhan
04:56
created

Authenticator::setUserRolesFromAudienceClaims()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 10
nc 5
nop 2
1
<?php
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
namespace KleijnWeb\JwtBundle\Authenticator;
9
10
use Symfony\Component\Security\Core\Authentication\SimplePreAuthenticatorInterface;
11
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
12
use Symfony\Component\Security\Core\Exception\AuthenticationException;
13
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
14
use Symfony\Component\HttpFoundation\Request;
15
use KleijnWeb\JwtBundle\User\UserInterface;
16
use Symfony\Component\Security\Core\User\UserProviderInterface;
17
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
18
19
/**
20
 * @author John Kleijn <[email protected]>
21
 */
22
class Authenticator implements SimplePreAuthenticatorInterface
0 ignored issues
show
Deprecated Code introduced by
The interface Symfony\Component\Securi...eAuthenticatorInterface has been deprecated with message: Since version 2.8, to be removed in 3.0. Use the same interface from Security\Http\Authentication instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
23
{
24
    /**
25
     * @var JwtKey[]
26
     */
27
    private $keys = [];
28
29
    /**
30
     * @param JwtKey[] $keys
31
     */
32
    public function __construct(array $keys)
33
    {
34
        foreach ($keys as $key) {
35
            $this->keys[$key->getId()] = $key;
36
        }
37
    }
38
39
    /**
40
     * @param string $id
41
     *
42
     * @return JwtKey
43
     */
44
    public function getKeyById($id)
45
    {
46
        if ($id) {
47
            if (!isset($this->keys[$id])) {
48
                throw new AuthenticationException("Unknown 'kid' $id");
49
            }
50
51
            return $this->keys[$id];
52
        }
53
        if (count($this->keys) > 1) {
54
            throw new AuthenticationException("Missing 'kid'");
55
        }
56
57
        return current($this->keys);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression current($this->keys); of type KleijnWeb\JwtBundle\Authenticator\JwtKey|false adds false to the return on line 57 which is incompatible with the return type documented by KleijnWeb\JwtBundle\Auth...thenticator::getKeyById of type KleijnWeb\JwtBundle\Authenticator\JwtKey. It seems like you forgot to handle an error condition.
Loading history...
58
    }
59
60
    /**
61
     * @param Request $request
62
     * @param string  $providerKey
63
     *
64
     * @return PreAuthenticatedToken
65
     */
66
    public function createToken(Request $request, $providerKey)
67
    {
68
        $tokenString = $request->headers->get('Authorization');
69
70
        if (0 === strpos($tokenString, 'Bearer ')) {
71
            $tokenString = substr($tokenString, 7);
72
        }
73
74
        if (!$tokenString) {
75
            throw new BadCredentialsException('No API key found');
76
        }
77
78
        try {
79
            $token = new JwtToken($tokenString);
80
            $key   = $this->getKeyById($token->getKeyId());
81
            $key->validateToken($token);
82
        } catch (\Exception $e) {
83
            throw new AuthenticationException('Invalid key', 0, $e);
84
        }
85
86
        return new PreAuthenticatedToken('anon.', $token, $providerKey);
87
    }
88
89
    /**
90
     * @param TokenInterface        $token
91
     * @param UserProviderInterface $userProvider
92
     * @param string                $providerKey
93
     *
94
     * @return PreAuthenticatedToken
95
     */
96
    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
97
    {
98
        /** @var $jwtToken JwtToken */
99
        if (!($jwtToken = $token->getCredentials()) instanceof JwtToken) {
100
            throw new \UnexpectedValueException("Expected credentials to be a JwtToken object");
101
        }
102
103
        $user = $userProvider->loadUserByUsername($jwtToken->getSubject());
0 ignored issues
show
Documentation introduced by
$jwtToken->getSubject() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
104
105
        if ($user instanceof UserInterface) {
106
            $user = $this->setUserRolesFromAudienceClaims($user, $token);
107
        }
108
109
        return new PreAuthenticatedToken($user, $token, $providerKey, $user->getRoles());
110
    }
111
112
    /**
113
     * @param TokenInterface $token
114
     * @param string         $providerKey
115
     *
116
     * @return bool
117
     */
118
    public function supportsToken(TokenInterface $token, $providerKey)
119
    {
120
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
121
    }
122
123
    /**
124
     * @param UserInterface  $user
125
     * @param TokenInterface $token
126
     *
127
     * @return UserInterface
128
     */
129
    public function setUserRolesFromAudienceClaims(UserInterface $user, TokenInterface $token)
130
    {
131
        /** @var JwtToken $credentials */
132
        $credentials = $token->getCredentials();
133
134
        foreach ($credentials->getClaims() as $claimKey => $claimValue) {
135
            if ($claimKey === 'aud') {
136
                if (is_array($claimValue)) {
137
                    foreach ($claimValue as $role) {
138
                        $user->addRole("ROLE_" . strtoupper($role));
139
                    }
140
                } elseif (is_string($claimValue)) {
141
                    $user->addRole("ROLE_" . strtoupper($claimValue));
142
                }
143
            }
144
        }
145
146
        return $user;
147
    }
148
}
149