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

标签 firewall logout symfony-security symfony5

我正在关注 excellent french course专为 symfony 4 设计并开始适应 symfony 5。

我正在尝试在用户进入管理/注销路由时创建重定向路由。 根据Symfony 5 official documentation ,我根本不需要在注销函数中写任何东西。

这是关于为管理员用户和没有权限的用户创建防火墙。实际上,我为管理员启用了一条注销路线,但它被解释而不是通过 security.yaml 进程注销管理员...... 原因是我在主防火墙中被阻止,而不是进入管理防火墙。 结果,Symfony 抛出这个 error in screenshot ,说: “ Controller 必须返回一个“Symfony\Component\HttpFoundation\Response”对象,但它返回了 null。您是否忘记在 Controller 中的某处添加 return 语句?”。

我想真正的问题是:我可以切换防火墙吗? 我的目标只是为普通用户和管理员用户提供正确的连接形式,以及传达他们自己的重定向路由的正确断开路由。 你有什么主意吗 ?我以为每当我使用/admin/* 路由时都会选择管理防火墙... 感谢您的帮助!

我将向您展示我的 security.yaml、routes.yaml、检查管理员登录表单的 Controller 、处理管理员/注销路由的 Controller 以及我的管理员注销按钮所在的 twig 模板。

在展示之前,我让您知道我可以同时登录管理员和普通用户。只有管​​理员注销路由被破坏。以下是文件。

1/5 安全.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 }


我的 routes.yaml 处理 app_admin_account_logout 路由:

app_admin_account_logout:
   path: /admin/logout
   methods: GET

3/5 AdminLoginFormAuthenticator.php 检查登录表单

<?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 处理管理/登录和管理/注销路由:

<?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 以及托管注销按钮的我的 Twig 标题模板的一部分:

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

最佳答案

是的,你可以喜欢这个

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

你不需要只在 security.yaml 中编辑 route.yaml 文件

关于firewall - Symfony 5 : Can I have a main and admin firewalls in security. yaml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60742898/

相关文章:

windows - 创建通过防火墙可见的本地服务器

即使添加新的防火墙规则后连接仍被拒绝

javascript - 阻止公众访问 expressjs 应用程序

python - 尝试注销 django 时出现运行时错误

php - iPad 上 Safari 中的用户超时

php - 使用注释的安全方法

Symfony 5 security.interactive_login 事件未调用

security - 从哪里开始网络安全

exit - 退出和注销的区别

php - 保护 symfony 3 中登录系统的安全