2012-01-29 35 views
21

Để đăng nhập thành công, có một tham số use_referer: true. Đối với lỗi đăng nhập, chỉ có failure_path, đó không phải là những gì tôi đang tìm kiếm.Cách quay lại tham chiếu sau khi đăng nhập thất bại?

Điều thứ hai: Cách thực hiện điều đó và chuyển thông báo lỗi?

Điều thứ ba: Cách quay lại liên kết giới thiệu sau khi đăng xuất?

+0

Tại sao đường dẫn thất bại không phải là dấu nhắc đăng nhập? – JamesHalsall

+1

vì tôi có thể đăng nhập từ mọi trang con. Tôi không có một mẫu đăng nhập trên url được chỉ định, vì vậy tôi không muốn chuyển hướng người dùng đến trang chủ khi anh ấy đăng nhập từ ví dụ như một trang hồ sơ người dùng khác. –

Trả lời

49

Tôi đã giải quyết.

Có giải pháp: How to disable redirection after login_check in Symfony 2

và đây là mã mà giải quyết vấn đề của tôi:

<?php 

namespace Acme\MainBundle\Handler; 

use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface; 
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface; 
use Symfony\Component\Security\Core\Exception\AuthenticationException; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\RedirectResponse; 

class AuthenticationHandler implements AuthenticationFailureHandlerInterface, LogoutSuccessHandlerInterface 
{ 
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception) 
    {  
     $referer = $request->headers->get('referer');  
     $request->getSession()->setFlash('error', $exception->getMessage()); 

     return new RedirectResponse($referer); 
    } 

    public function onLogoutSuccess(Request $request) 
    { 
     $referer = $request->headers->get('referer'); 
     return new RedirectResponse($referer); 
    } 
} 

để xử lý các sự kiện thêm vào security.yml ví dụ:

form_login: 
    check_path: /access/login_check 
    login_path:/
    use_referer: true 
    failure_handler: authentication_handler 
logout: 
    path: /access/logout 
    target:/
    success_handler: authentication_handler 

và để cấu hình .yml:

services: 
    authentication_handler: 
     class: Acme\MainBundle\Handler\AuthenticationHandler 
+4

$ request-> headers-> get ('referer'); đôi khi trả về null (tôi đã sao chép trong Firefox). Giải pháp này không đáng tin cậy, một dự phòng hoặc giải pháp khác là cần thiết. – Julien

+0

@ wojciech-kulik Tôi có lỗi sau: '' '$ request-> getSession() -> setFlash ('lỗi', $ exception-> getMessage());' '' '' 'FatalErrorException: Lỗi: Gọi hàm undefined Symfony \ Component \ HttpFoundation \ Session \ Session :: setFlash() trong /var/www/symfony/src/Application/Sonata/UserBundle/Form/Handler/AuthenticationHandler.php dòng 16''' – jcarlosweb

+0

@webyseo Probably bạn đã có một phiên bản khác nhau của Symphony và thông điệp flash được thiết lập theo một cách khác. Có thể nó sẽ giúp: http://stackoverflow.com/questions/13348534/symfony-2-setting-a-flash-message-outside-of-controller –

Các vấn đề liên quan