Подтвердить что ты не робот

Как symfony2 перенаправляется на запрашиваемую страницу после входа в систему

Скажем, мой маршрут /booking/(.*) защищен конфигурацией брандмауэра в security.yml, и для этого требуется ROLE_USER, когда пользователь пытается получить доступ к любому маршруту, которому предшествует "/booking/", приложение перенаправляет пользователя на страницу входа для аутентификации.

Итак, мой вопрос заключается в том, что после того, как пользователь предоставит свои учетные данные и получит аутентификацию, как Symfony 2 может перенаправить пользователя на страницу/маршрут, который пользователь запросил для OR, где Symfony 2 хранит этот маршрут хранит ли он его в какой-либо сессии или где-то еще.

Можем ли мы получить к нему доступ и как?

4b9b3361

Ответ 1

Это возможно, и вы можете получить доступ к ссылочной ссылке (которая используется, если use_referer установлена ​​в true) в сеансе.

Например, если на вашем form_login (в конфигурации брандмауэра) есть служба success_handler, которая перенаправляет пользователей на основе некоторых критериев (обычно роли), но вы хотите перенаправить пользователя на ссылку реферера, если она была вы можете получить доступ к ссылке-рефереру так:

$key = '_security.main.target_path'; #where "main" is your firewall name

//check if the referrer session key has been set 
if ($this->container->get('session')->has($key)) {
    //set the url based on the link they were trying to access before being authenticated
    $url = $this->container->get('session')->get($key);

    //remove the session key
    $this->container->get('session')->remove($key);
}
//if the referrer key was never set, redirect to a default route
else{
    $url = $this->router->generate('member_home');
}

return new RedirectResponse($url); 

Использование заголовка для получения реферера (т.е. $request->headers->get('referer')) не будет работать в этом случае, потому что оно всегда будет возвращать ссылку для входа.

Спасибо Роману Маринсенко и Райану Уиверу за это blog

Ответ 2

Решение Carrie Kendall работало, спасибо!

Вот полная реализация в Symfony:

services.yml:

login_handler:
    class: Project\BaseBundle\Service\loginHandler
    arguments: ['@router', '@doctrine.orm.entity_manager', '@service_container']

и в Project\BaseBundle\Service\loginHandler:

namespace Project\BaseBundle\Service;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Routing\RouterInterface;
use Doctrine\ORM\EntityManager;


class loginHandler implements AuthenticationSuccessHandlerInterface {

    private $router;
    private $container;
    private static $key;

    public function __construct(RouterInterface $router, EntityManager $em, $container) {

        self::$key = '_security.secured_area.target_path';

        $this->router = $router;
        $this->em = $em;
        $this->session = $container->get('session');

    }

    public function onAuthenticationSuccess( Request $request, TokenInterface $token ) {

        $user_entity = $token->getUser();

        if( !$user_entity->getChangePassword() ) {

            $route = $this->router->generate('BaseBundle_home_page');

        } else {

            $this->session->getFlashBag()->add('error', 'Your password must be changed now');

            $route = $this->router->generate('BaseBundle_account_page');

        }

        //check if the referer session key has been set
        if ($this->session->has( self::$key )) {

            //set the url based on the link they were trying to access before being authenticated
            $route = $this->session->get( self::$key );

            //remove the session key
            $this->session->remove( self::$key );
            //if the referer key was never set, redirect to a default route

        } else{

            $url = $this->generateUrl('BaseBundle_home_page');

            return new RedirectResponse($route);

        }

        return new RedirectResponse($route);

    }
}

Ответ 3

У меня тоже была эта проблема. Я использовал security.yml и в используемом действии регистрации:

$redirectUrl = $request->getSession()->get('_security.account.target_path');

пользоваться.

Ответ 4

Symfony использует HTTP Referer header, чтобы перенаправить пользователя обратно на страницу, из которой они пришли.. ie referrer

Вы можете установить это с помощью конфигурации безопасности use_referer: true в разделе security.yml, здесь

Вы можете получить доступ к заголовку реферера с контроллера, используя следующее:

$referer = $request->headers->get('referer');

Примечание заголовок пропущен, его референт (один r)