[Symfony 5] Подтверждение сообщения после выхода из системы - PullRequest
0 голосов
/ 02 апреля 2020

На Symfony 5, используя встроенную систему входа в систему, кажется невозможным добавить подтверждающее сообщение после выхода из системы. Я строго следовал шагам, описанным на официальном сайте . К сожалению, выход из системы внутри SecurityController бесполезен. Я перенаправлен прямо на страницу входа.

Здесь у вас будет мой файл security.yaml:

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


# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
    # used to reload user from session & other features (e.g. switch_user)
    app_user_provider:
        entity:
            class: App\Entity\User
            property: email
    # used to reload user from session & other features (e.g. switch_user)
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: lazy
        provider: app_user_provider
        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
        logout:
            path: logout
            target: login

        remember_me:
            secret:   '%kernel.secret%'
            lifetime: 604800 # 1 week in seconds
            path:     home
            always_remember_me: true

        # 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: ^/logout$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: IS_AUTHENTICATED_FULLY }
    - { path: ^/admin, roles: [IS_AUTHENTICATED_FULLY, ROLE_ADMIN] }
    - { path: ^/profile, roles: [IS_AUTHENTICATED_FULLY, ROLE_USER] }

И контроллер:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        if ($this->getUser()) {
            return $this->redirectToRoute('home');
        }

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        return $this->render('security/login.html.twig', ['last_username' => null, 'error' => $error]);
    }

    public function logout()
    {
        throw new \Exception('Don\'t forget to activate logout in security.yaml');
    }
}

?>

Спасибо за вашу помощь!

Ответы [ 2 ]

0 голосов
/ 03 апреля 2020

Благодаря Indra Gunawan это решение работает. Моя цель состояла в том, чтобы перенаправить на страницу входа с сообщением типа «Вы успешно вышли из системы».

В этом случае LogoutSuccessHandler должен быть адаптирован для маршрутизации на страницу входа:

namespace App\Logout;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

class MyLogoutSuccessHandler extends AbstractController implements LogoutSuccessHandlerInterface
{

    private $urlGenerator;

    public function __construct(UrlGeneratorInterface $urlGenerator)
    {
        $this->urlGenerator = $urlGenerator;
    }

    public function onLogoutSuccess(Request $request)
    {
        return new RedirectResponse($this->urlGenerator->generate('login', ['logout' => 'success']));
    }
}

Маршрутный логин должен быть определен в маршрутах

Последнее, вы можете поймать параметр выхода из системы в шаблоне ветки, например:

    {%- if app.request('logout') -%}
        <div class="alert alert-success">{% trans %}Logout successful{% endtrans %}</div>
    {%- endif -%}   
0 голосов
/ 02 апреля 2020

метод выхода из системы в SecurityController фактически не будет вызван, потому что Symfony будет перехватывать запрос. если вам нужно что-то сделать после выхода из системы, вы можете использовать обработчик успеха при выходе из системы

namespace App\Logout;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;

class MyLogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public function onLogoutSuccess(Request $request)
    {
        // you can do anything here
        return new Response('logout successfully'); // or render a twig template here, it's up to you
    }
}

и зарегистрировать свой обработчик успеха при выходе из системы в security.yaml

firewalls:
    main:
        anonymous: lazy
        provider: app_user_provider
        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
        logout:
            path: logout
            success_handler: App\Logout\MyLogoutSuccessHandler # assume you have enable autoconfigure for servicess or you need to register the handler
...