2016-07-22 55 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 

享受!