3

我正在学习为 symfony 4 设计的优秀法语课程,并开始适应 symfony 5。

当用户使用管理员/注销路由时,我正在尝试创建重定向路由。根据Symfony 5 官方文档,我根本不需要在注销功能中写任何东西。

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

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

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

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

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 处理 admin/login 和 admin/logout 路由:

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

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

1 回答 1

2

是的,你可以喜欢这个

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 文件

于 2020-03-30T05:59:33.410 回答