23. SonataAdmin without SonataUserBundle

Here we will explain how you can use SonataAdmin with Symfony Guard instead of using SonataUserBundle.

Code used in this short guide can be found here with support for different Symfony versions.

23.1. The recipe

Things we will need to setup:

23.1.1. User Entity

This represents your security user, you can read more about it here:

namespace App\Entity;

use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

class User implements UserInterface
    #[ORM\Column(type: Types::INTEGER)]
    private ?int $id = null;

    #[ORM\Column(type: Types::STRING, unique: true)]
    private ?string $email = null;

    #[ORM\Column(type: Types::STRING, nullable: true)]
    private ?string $password = null;

    #[ORM\Column(type: Types::ARRAY)]
    private array $roles = [];

23.1.2. UserProvider

This represents your user provider, it will be used to load your security users, read more about it here:

namespace App\Security;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

final class UserProvider implements UserProviderInterface
    private EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
        $this->entityManager = $entityManager;

    public function loadUserByUsername($email): User
        $user = $this->findOneUserBy(['email' => $email]);

        if (!$user) {
            throw new UsernameNotFoundException(
                    'User with "%s" email does not exist.',

        return $user;

    private function findOneUserBy(array $options): ?User
        return $this->entityManager

    public function refreshUser(UserInterface $user): User
        assert($user instanceof User);

        if (null === $reloadedUser = $this->findOneUserBy(['id' => $user->getId()])) {
            throw new UsernameNotFoundException(sprintf(
                'User with ID "%s" could not be reloaded.',

        return $reloadedUser;

    public function supportsClass($class): bool
        return $class === User::class;

23.1.3. AdminLoginForm

A small login form that will validate our data:

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;

final class AdminLoginForm extends AbstractType
    public function buildForm(FormBuilderInterface $builder, array $options): void
            ->add('email', EmailType::class)
            ->add('password', PasswordType::class);

23.1.4. AdminLoginAuthenticator

This represents your custom authentication system, read more about it here:

namespace App\Security;

use App\Form\AdminLoginForm;
use App\Entity\User;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Guard\AuthenticatorInterface;

final class AdminLoginAuthenticator extends AbstractFormLoginAuthenticator implements AuthenticatorInterface
    private FormFactoryInterface $formFactory;

    private RouterInterface $router;

    private UserPasswordEncoderInterface $passwordEncoder;

    public function __construct(
        FormFactoryInterface $formFactory,
        RouterInterface $router,
        UserPasswordEncoderInterface $passwordEncoder
    ) {
        $this->formFactory = $formFactory;
        $this->router = $router;
        $this->passwordEncoder = $passwordEncoder;

    public function supports(Request $request): bool
        return $request->attributes->get('_route') === 'admin_login' && $request->isMethod('POST');

    public function getCredentials(Request $request): array
        $form = $this->formFactory->create(AdminLoginForm::class);

        $data = $form->getData();

        return $data;

    public function getUser($credentials, UserProviderInterface $userProvider): UserInterface
        return $userProvider->loadUserByUsername($credentials['email']);

    public function checkCredentials($credentials, UserInterface $user): bool
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): RedirectResponse
        $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);

        return new RedirectResponse($this->router->generate('admin_login'));

    protected function getLoginUrl(): string
        return $this->router->generate('admin_login');

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): RedirectResponse
        return new RedirectResponse($this->router->generate('sonata_admin_dashboard'));

23.1.5. AdminLoginController

A Controller, used to render login form. Logout is left empty intentionally because this will be handled by Symfony, but we still need to register that route:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Form\AdminLoginForm;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\HttpFoundation\Response;

final class AdminLoginController extends AbstractController
    private AuthenticationUtils $authenticationUtils;

    public function __construct(AuthenticationUtils $authenticationUtils)
        $this->authenticationUtils = $authenticationUtils;

    #[Route('/admin/login', name: 'admin_login')]
    public function loginAction(): Response
        $form = $this->createForm(AdminLoginForm::class, [
            'email' => $this->authenticationUtils->getLastUsername()

        return $this->render('security/login.html.twig', [
            'last_username' => $this->authenticationUtils->getLastUsername(),
            'form' => $form->createView(),
            'error' => $this->authenticationUtils->getLastAuthenticationError(),

    #[Route('/admin/logout', name: 'admin_logout')]
    public function logoutAction(): void
        // Left empty intentionally because this will be handled by Symfony.

23.1.6. Setup firewall in security.yaml

# config/packages/security.yaml


        App\Entity\User: auto # use bcrypt if you are using "symfony/security-bundle" < 4.3

            id: App\Security\UserProvider

        # Disabling the security for the web debug toolbar, the profiler and Assetic.
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false
        # -> custom firewall for the admin area of the URL
            pattern:            /admin(.*)
                provider:       users
                login_path:     admin_login
                use_forward:    false
                check_path:     admin_login
                failure_path:   null
                path:           admin_logout
                target:         admin_login
            anonymous:          true
                    - App\Security\AdminLoginAuthenticator
            anonymous: ~

    - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN] }
    - { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }

23.1.7. Login template resembling Sonata style

{# templates/security/login.html.twig #}

{% extends '@SonataAdmin/standard_layout.html.twig' %}

{% block sonata_nav %}
{% endblock sonata_nav %}

{% block logo %}
{% endblock logo %}

{% block sonata_left_side %}
{% endblock sonata_left_side %}

{% block body_attributes %}class="sonata-bc login-page"{% endblock %}

{% block sonata_wrapper %}
    <div class="login-box">
        <div class="login-logo">
            <a href="{{ path('sonata_admin_dashboard') }}">
        <div class="login-box-body">
            {% block sonata_user_login_form %}
                {% block sonata_user_login_error %}
                    {% if error %}
                        <div class="alert alert-danger">
                            {{ error.messageKey|trans(error.messageData, 'security') }}
                    {% endif %}
                {% endblock %}
                {% for label, flashes in app.session.flashbag.all %}
                    {% for flash in flashes %}
                        <div class="alert alert-{{ label }}">
                            {{ flash }}
                    {% endfor %}
                {% endfor %}
                <p class="login-box-msg">{{ 'Authentication'|trans }}</p>
                <form action="{{ path("admin_login") }}" method="post" role="form">
                    {{ form_row(form._token) }}

                    <div class="form-group has-feedback">
                        <input type="text" class="form-control" id="username" name="{{ form.email.vars.full_name }}" value="{{ last_username }}" required="required" placeholder="Email"/>
                        <span class="glyphicon glyphicon-user form-control-feedback"></span>

                    <div class="form-group has-feedback">
                        <input type="password" class="form-control" id="password" name="{{ form.password.vars.full_name }}" required="required" placeholder="Password"/>
                        <span class="glyphicon glyphicon-lock form-control-feedback"></span>

                    <div class="row">
                        <div class="col-xs-4">
                            <button type="submit" class="btn btn-primary btn-block btn-flat">Login</button>
            {% endblock %}
{% endblock sonata_wrapper %}

The login form will look like this:

Login Form