Newer
Older
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
<?php
/**
* This file is a part of SymfonySecurity package.
*
* (c) Nekland <dev@nekland.fr>
*
* For the full license, take a look to the LICENSE file
* on the root directory of this project
*/
namespace BiiG\SecurityTest;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Class CustomAuthenticationProvider
* @package BiiG\SecurityTest
*
* Pourrait hériter de UserAuthenticationProvider pour simplifier le traitement d'un utilisateur standard.
*/
class CustomAuthenticationProvider implements AuthenticationProviderInterface
{
private $userProvider;
private $encoderFactory;
public function __construct()
{
$this->userProvider = new InMemoryUserProvider(
array(
'admin' => array(
// password is "foo"
'password' => '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==',
'roles' => array('ROLE_ADMIN'),
),
)
);
$this->encoderFactory = new EncoderFactory([
User::class => new MessageDigestPasswordEncoder('sha512', true, 5000)
]);
}
public function authenticate(TokenInterface $token)
{
$user = $this->userProvider->loadUserByUsername($token->getUsername());
// Un certain nombre de cas comme celui-ci sont à gérer
if (!$user instanceof UserInterface) {
throw new AuthenticationServiceException('The user provider must return a UserInterface object.');
}
$encoder = $this->encoderFactory->getEncoder($user);
if (!$encoder->isPasswordValid($user->getPassword(), $token->getCredentials(), $user->getSalt())) {
throw new BadCredentialsException('The presented password is invalid.');
}
$token->setUser($user);
$token->setAuthenticated(true);
return $token;
}
public function supports(TokenInterface $token)
{
return $token instanceof UsernamePasswordToken;
}
}