2016-07-22 106 views
0

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

回答

1

我已经找出解决方案。我们需要扩展Symfony安全组件DefaultAuthenticationSuccessHandler,以更具体 - determineTargetUrl方法。

这段代码是负责的URL,会话结束

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,创建处理程序,我在Vendor/YourBundle/Handle目录添加AuthenticationHandler.php

<?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 

享受!