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
<?php
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
class ApiKeyUserProvider implements UserProviderInterface
{
public function __construct(EntityManagerInterface $manager)
{
$this->manager = $manager;
}
public function getUsernameForApiKey($apiKey)
{
$user = $this->manager->getRepository(User::class)
->findOneByApiKey($apiKey);
if (!$user) {
return null;
}
return $user->getUsername();
}
public function loadUserByUsername($username)
{
return $this->manager->getRepository(User::class)
->findOneByUsername($username);
}
public function refreshUser(UserInterface $user)
{
// this is used for storing authentication in the session
// but in this example, the token is sent in each request,
// so authentication can be stateless. Throwing this exception
// is proper to make things stateless
throw new UnsupportedUserException();
}
public function supportsClass($class)
{
return User::class === $class;
}
}