Search code examples
firewalllogoutsymfony-securitysymfony5

Symfony 5: Can I have a main and admin firewalls in security.yaml?


I am following an excellent french course designed for symfony 4 and starting getting adapted to symfony 5.

I am trying to create a redirection route when an user goes on admin/logout route. According to Symfony 5 official documentation, I do not have to write anything at all inside the logout function.

This is about creating firewall for admin users and those with no privileges. Actually, I enabled a route for admins to log out but it is interpreted instead of loging out admin through security.yaml process... The reason is I stay blocked in main firewall instead going into admin firewall. As a consequence, Symfony throws this error in screenshot, saying: "The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned null. Did you forget to add a return statement somewhere in your controller?".

I guess the true question is: Can I switch of firewall ? My goal is just to have for both normal user and admin user their proper connection form, and proper disconnection route conveying their own redirection route. Do you have any idea ? I thought admin firewall would be selected whenever I use a /admin/* route... Thanks for your help !

I am going to show you my security.yaml, routes.yaml, the controller examining the admin login form, the controller handling admin/logout route and my twig template where my admin logout button is.

Just before showing, I let you know I can log in for both admin and normal user. Only the admin logout route is broken. Below, are the files.

1/5 security.yaml :

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory: { memory: null }
        in_database: 
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        admin:
            pattern: ˆ/admin
            anonymous: true
            provider: in_database
            form_login:
                login_path: admin_account_login
                check_path: admin_account_login
            logout:
                path: app_admin_account_logout
                target: homepage
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator

        main:
            context: normal
            anonymous: true
            provider: in_database
            form_login: 
                login_path: account_login
                check_path: account_login
            logout:
                path: account_logout
                target: account_login
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator
                    - App\Security\AdminLoginFormAuthenticator
                entry_point: App\Security\LoginFormAuthenticator


            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#firewalls-authentication

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: '^/admin/login', roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: '^/admin', roles: ROLE_ADMIN }
        # - { path: ^/profile, roles: ROLE_USER }


my routes.yaml handling the app_admin_account_logout route:

app_admin_account_logout:
   path: /admin/logout
   methods: GET

3/5 AdminLoginFormAuthenticator.php examining the login form

<?php

namespace App\Security;

use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
// use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
// use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
// use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;

class AdminLoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
    use TargetPathTrait;

    private $userRepository;
    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $passwordEncoder;

    public function __construct(UserRepository $userRepository, EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;

        $this->userRepository = $userRepository;
    }

    public function supports(Request $request)
    {
        // die('Our authenticator is alive!');    
        return 'admin_account_login' === $request->attributes->get('_route')
            && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        // dd($request->request->all());
        $credentials = [
            'email' => $request->request->get('_username'),
            'password' => $request->request->get('_password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        // dd($credentials);
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['email']
        );

        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        // dd($credentials);
        return $this->userRepository->findOneBy(['email' => $credentials['email']]);

        // $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        // if (!$this->csrfTokenManager->isTokenValid($token)) {
        //     throw new InvalidCsrfTokenException();
        // }

        // $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);

        // if (!$user) {
        //     // fail authentication with a custom error
        //     throw new CustomUserMessageAuthenticationException('Email could not be found.');
        // }

        // return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        // dd($user);
        // return true;
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function getPassword($credentials): ?string
    {
        return $credentials['password'];
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        // dd('success');
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
        // throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
        return new RedirectResponse($this->urlGenerator->generate('admin_ads_index'));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('admin_account_login');
    }
}

4/5 AdminAccountController.php handling admin/login and admin/logout routes:

<?php

namespace App\Controller;

use App\Security\AdminFormAuthenticator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\Request;

class AdminAccountController extends AbstractController
{
    /**
     * Require ROLE_ADMIN for only this controller method.
     * @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
     * @Route("/admin/login", name="admin_account_login")
     */
    public function login(AuthenticationUtils $authenticationUtils)
    {
        // if ($this->getUser()) {
        //     return $this->redirectToRoute('target_path');
        // }

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('admin/account/login.html.twig', [
            'hasError' => $error !== null,
            'username' => $lastUsername
        ]);
    }

   /**
    * Allows admin user to log out
    * @Route("/admin/logout", name="admin_account_logout", methods={"GET"})
    * @return void
    */
    public function logout() {
        throw new \Exception('Will be intercepted before getting here');
    }
}

5/5 And a part of my twig header template hosting the logout button :

                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="accountDropdownLink">
                        <a href="{{ path('app_admin_account_logout')}}" class="dropdown-item">Déconnexion</a>
                    </div>

Solution

  • yes you can like this

    fierWallName:
            anonymous: lazy
            provider: in_database
            form_login:
                login_path: login #login of this fier wall route name
                check_path: login #login of this fier wall route name 
            logout:
                path: logout #logout of this fier wall route name
                target: home_page #target route name
    

    you do not need to edit the route.yaml file just in security.yaml