Skip to content
Snippets Groups Projects
CustomAuthenticationProvider.php 2.7 KiB
Newer Older
Maxime Veber's avatar
Maxime Veber committed
<?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.');
        }
Maxime Veber's avatar
Maxime Veber committed

        $token->setUser($user);
        $token->setAuthenticated(true);

        return $token;
Maxime Veber's avatar
Maxime Veber committed
    }

    public function supports(TokenInterface $token)
    {
        return $token instanceof UsernamePasswordToken;
    }
}