-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathApiKeyProvider.php
More file actions
90 lines (78 loc) · 2.8 KB
/
ApiKeyProvider.php
File metadata and controls
90 lines (78 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace Uecode\Bundle\ApiKeyBundle\Security\Authentication\Provider;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\ChainUserProvider;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Uecode\Bundle\ApiKeyBundle\Security\Authentication\Token\ApiKeyUserToken;
/**
* @author Aaron Scherer <aequasi@gmail.com>
*/
class ApiKeyProvider implements AuthenticationProviderInterface
{
private UserProviderInterface $userProvider;
public function __construct(UserProviderInterface $userProvider)
{
$this->userProvider = $userProvider;
}
/**
* Attempts to authenticate a TokenInterface object.
*
* @param TokenInterface $token The TokenInterface instance to authenticate
*
* @return TokenInterface|null An authenticated TokenInterface instance, never null
*
* @throws AuthenticationException if the authentication fails
*/
public function authenticate(TokenInterface $token)
{
if($this->userProvider instanceof ChainUserProvider) {
foreach ($this->userProvider->getProviders() as $provider) {
$result = $this->doAuth($provider, $token);
if($result !== false) {
return $result;
}
}
} else {
$result = $this->doAuth($this->userProvider, $token);
if ($result !== false) {
return $result;
}
}
return null;
}
/**
* @param UserProviderInterface $provider
* @param TokenInterface $token
*
* @return bool|ApiKeyUserToken
* @throws AuthenticationException
*/
protected function doAuth($provider, TokenInterface $token)
{
if (! $provider instanceof ApiKeyUserProviderInterface) {
return false;
}
/** @var UserInterface $user */
$user = $provider->loadUserByApiKey($token->getCredentials());
if ($user) {
$authenticatedToken = new ApiKeyUserToken($user->getRoles());
$authenticatedToken->setUser($user);
return $authenticatedToken;
}
throw new AuthenticationException("The API Key authentication failed.");
}
/**
* Checks whether this provider supports the given token.
*
* @param TokenInterface $token A TokenInterface instance
*
* @return Boolean true if the implementation supports the Token, false otherwise
*/
public function supports(TokenInterface $token)
{
return $token instanceof ApiKeyUserToken;
}
}