Completed
Pull Request — master (#15)
by Oguzhan
02:18
created

Authenticator::setUserRolesFromAudienceClaims()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.2222
c 0
b 0
f 0
cc 7
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 Symfony\Component\Security\Core\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
        $user = $this->setUserRolesFromAudienceClaims($user, $token);
106
107
        return new PreAuthenticatedToken($user, $token, $providerKey, $user->getRoles());
108
    }
109
110
    /**
111
     * @param TokenInterface $token
112
     * @param string         $providerKey
113
     *
114
     * @return bool
115
     */
116
    public function supportsToken(TokenInterface $token, $providerKey)
117
    {
118
        return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
119
    }
120
121
    /**
122
     * @param UserInterface  $user
123
     * @param TokenInterface $token
124
     *
125
     * @return UserInterface
126
     */
127
    public function setUserRolesFromAudienceClaims(UserInterface $user, TokenInterface $token)
128
    {
129
        /** @var JwtToken $credentials */
130
        $credentials = $token->getCredentials();
131
132
        foreach($credentials->getClaims() as $claimKey => $claimValue)
133
        {
134
            if($claimKey === 'aud' && method_exists($user, 'addRole')) {
135
                if(is_array($claimValue)) {
136
                    foreach($claimValue as $role) {
137
                        $user->addRole($role);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Security\Core\User\UserInterface as the method addRole() does only exist in the following implementations of said interface: KleijnWeb\JwtBundle\Tests\Classes\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
138
                    }
139
                } elseif(is_string($claimValue)) {
140
                    $user->addRole($claimValue);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Security\Core\User\UserInterface as the method addRole() does only exist in the following implementations of said interface: KleijnWeb\JwtBundle\Tests\Classes\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
141
                }
142
            }
143
        }
144
145
        return $user;
146
    }
147
}
148