Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Login use_referer not working

Tags:

php

symfony

Here's my security.yml for user login:

user_secured_area:
        pattern: /*
        anonymous: ~
        provider: user
        form_login:
            check_path: /login_check
            login_path: /login
            use_referer: true
            username_parameter: _email
        logout:
            path: logout
            target: /

I've checked the profiler for HTTP_REFERRER and i've got the correct referer. However upon login, it is redirected to the root URL and not the referer URL. Any idea on this or have i missed out something?

The controller:

public function indexAction(Request $request){

    $session = $request->getSession();

    //get login error
    if($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)){
        $error = $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR);
    }
    else if(null!==$session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)){
        $error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR);
        $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
    }
    else{
        $error = "";
    }

    //repopulate username
    $lastEmail = (null === $session) ? '' : $session->get(SecurityContextInterface::LAST_USERNAME); // a ? true : false

    return $this->render('BazaarBundle:Login:login.html.twig', array('last_email' => $lastEmail, 'error' => $error));
}

The twig:

<form action="{{ path('login_check') }}" method="post">
<label for="email">Email:</label>
<input type="text" id="email" name="_email" value="{{ last_email }}" />

<label for="password">Password:</label>
<input type="password" id="password" name="_password" />

<button type="submit">login</button>

like image 297
Karl Wong Avatar asked Jan 16 '15 15:01

Karl Wong


Video Answer


1 Answers

The default behavior is to redirect on the asked page after login.

The use_referer option is used only if no URL is stored in session. Otherwise, you're redirected to the default target path (which can be defined by using the default_target_path option) or the default page ('/') if no parameters defined.

Please look into the Session Attributes ine the Symfony debugger (when you're on the login page). Do you have a _security.yourfirewall.target_path record ? What is the value ?

EDIT: It seems that the session variable is only defined if you're automatically redirected to the login page (for exemple when trying to acces to a secured area without the required rights).

Another possibility is to add an hidden field named _target_path with the wanted value (exemple below).

Adding target_path by the form (maybe it should be good to check if it's not empty):

<input type="hidden" name="_target_path" value="{{ app.request.headers.get('referer') }}" />

Cheers

like image 95
Jona Avatar answered Nov 14 '22 23:11

Jona