重新登录后修改symfony重定向路径

时间:2016-07-22 07:36:37

标签: symfony redirect

我看过很多类似的问题,但还没有找到答案。 好吧,当会话到期时,用户将被重定向到登录页面。 然后,用户插入登录名/密码,symfony将他重定向到上一页,如/page。 我想将用户重定向到#/page,因此我需要将/#字符串添加到referer路径。我怎样才能做到这一点? 我使用的是FOSUserBundle,但看起来就像symfony那样。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我已经找到了解决方案。我们需要扩展Symfony安全组件DefaultAuthenticationSuccessHandler,更具体地说是determineTargetUrl方法。

这段代码负责会话结束后的网址

if (null !== $this->providerKey && $targetUrl = $request->getSession()->get('_security.'.$this->providerKey.'.target_path')) {
            $request->getSession()->remove('_security.'.$this->providerKey.'.target_path');

           return $targetUrl;
        }

因此,让我们扩展此类并修改$targetUrl值。

Firstable,创建处理程序,我添加了AuthenticationHandler.php  在Vendor/YourBundle/Handle目录

<?php

namespace Vendor\YourBundle\Handler;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\Security\Http\ParameterBagUtils;

class AuthenticationHandler extends DefaultAuthenticationSuccessHandler
{
    protected function determineTargetUrl(Request $request)
    {
        if ($this->options['always_use_default_target_path']) {
            return $this->options['default_target_path'];
        }

        if ($targetUrl = ParameterBagUtils::getRequestParameterValue($request, $this->options['target_path_parameter'])) {
            return $targetUrl;
        }

        if (null !== $this->providerKey && $targetUrl = $request->getSession()->get('_security.'.$this->providerKey.'.target_path')) {
            $request->getSession()->remove('_security.'.$this->providerKey.'.target_path');

            $arr = explode('//', $targetUrl);
            $arr[1] = explode('/', $arr[1]);
            $arr[1][0] .= "/#";
            $arr[1] = implode('/', $arr[1]);
            $arr = implode('//', $arr);

            return $arr;
        }

        if ($this->options['use_referer'] && ($targetUrl = $request->headers->get('Referer')) && $targetUrl !== $this->httpUtils->generateUri($request, $this->options['login_path'])) {
            return $targetUrl;
        }

        return $this->options['default_target_path'];
    }
}

注册服务:

#services.yml

services:
    authentication_handler:
        class: Vendor\YourBundle\Handler\AuthenticationHandler
        arguments:  ["@security.http_utils", {}]
        tags:
            - { name: 'monolog.logger', channel: 'security' }

定义处理程序:

#security.yml

     form_login:
         success_handler: authentication_handler

享受!