Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid CSRF token on my own login form

I'm working on a symfony application using FOSUserBundle. I want to have a dropdown login form in the menubar if i am not authenticated, which have a complete different style that the one under /login.

I'm getting 'Invalid CSRF token'. I'm a complete newbie to symfony2, so maybe i'm making an obvious mistake, but i can't find a solution googling. This is what i tried:

Controller:

<?php

namespace RoiRodriguez\CustomUserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\SecurityContext;

class DefaultController extends Controller {

    /**
     * Para requests internos, renderiza la barra de navegación.
     * No tiene ruta.
     */
    public function navigationAction() {
        $params = array (
                'csrf_token' => '',
                'last_username' => '' 
        );

        if ($this->container->get ( 'security.context' )->isGranted ( 'IS_AUTHENTICATED_FULLY' )) {
            $session = $this->getRequest ()->getSession ();
            $params ['last_username'] = (null === $session) ? '' : $session->get ( SecurityContext::LAST_USERNAME );
            $params ['csrf_token'] = $this->container->get ( 'form.csrf_provider' )->generateCsrfToken ( 'authenticate' );
        }

        return $this->render ( 'CustomUserBundle:Default:navigation.html.twig', $params );
    }
}

View:

<ul class="nav navbar-nav navbar-right">
{% if app.user and app.user.isGranted('IS_AUTHENTICATED_FULLY') %}
    {% include 'CustomUserBundle:Default:includes/navigation-authenticated.html.twig' %}
{% else %}
    {% include 'CustomUserBundle:Default:includes/navigation-notauthenticated.html.twig' with {'csrf_token': csrf_token, 'last_username': last_username} %}
{% endif %}
</ul>

Not authenticated template:

<li><a href="{{ path('fos_user_registration_register') }}">Nueva cuenta</a></li>
<li class="dropdown"><a href="#" class="dropdown-toggle"
    data-toggle="dropdown">Ingresar <b class="caret"></b></a>
    <div class="dropdown-menu dd-login-form-container">

        <!-- login form -->
        <form role="form" method="post"
            action="{{ path("fos_user_security_check") }}">
            <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />
......
            <button type="submit" class="btn btn-primary">Ingresa!</button>
        </form>
        <!-- end login form -->
        <ul>
            <li><a href="{{ path('fos_user_resetting_request') }}">¿Has olvidado
                    tu contraseña?</a></li>
            <li><a href="{{ path('fos_user_registration_register') }}">¿Todavía
                    no tienes una cuenta?</a></li>
        </ul>
    </div>
</li>

What am i missing? Also: This dropdown menu gets rendered inside /login too, would i have any trouble with generating the token twice there?

like image 906
roirodriguez Avatar asked Dec 08 '13 14:12

roirodriguez


4 Answers

My custom login form was giving me the same issue - 'Invalid CSRF token' - anytime I tried to log in. After going through the documentation for the FOSUserBundle configuration options(FOSUserBundle Configuration Reference), I discovered that the bundle enables a different token manager by default. So I went to my security.yml file and commented out the line specifying a csrf token generator for the login form.

Here is a cross section of my app/config/security.yml file with the configuration specifying the crsf token manager comment out.

security:

.......

firewalls:

    ........

    vendor:
        pattern: ^/vendor
        form_login:
            provider: fos_userbundle
        #   csrf_token_generator: security.csrf.token_manager
            login_path: vendor_login
            check_path: vendor_login_check
        logout: true

After doing this, my login form started working and I could log in.

like image 149
king Avatar answered Oct 22 '22 13:10

king


Here is the best and cleanest solution for this problem: set the csrf provider as a Twig global variable: https://stackoverflow.com/a/17233953/1399706

like image 6
Aerendir Avatar answered Oct 22 '22 13:10

Aerendir


I had the same problem in the past...

<form action="{{ path('yourRoute') }}" method="post" {{ form_enctype(form) }}>

The CSRF token was invalide because i didn't insert {{ form_enctype(form) }}

You should take a look at http://symfony.com/doc/current/reference/forms/twig_reference.html#form-enctype-view because this way will be removed soon...

like image 2
BENARD Patrick Avatar answered Oct 22 '22 12:10

BENARD Patrick


@Roirodriguez, your code help me get throught this. I think you just needed to call the render method instead of the include (my step 4).

I wanted to do a simple login form on my header, if any error occurred it will redirect you to the FOSUserBundle normal login page providing feedback. After the user was authenticated I wanted a dropdown with the username, when opened more options would showup (logout link, etc.)

Here is how I manage to get it working:

  1. Created a Child bundle of the FOSUserBundle. I Created a new bundle name UserBundle and then used the get parent method. link to FOSUserBundle docs

    <?php 
    namespace Me\UserBundle;
    use Symfony\Component\HttpKernel\Bundle\Bundle;
    class MeUserBundle extends Bundle
    {
        public function getParent()
        {
            return 'FOSUserBundle';
        }
    }
    
  2. Create Templates Created a new template for this new login form and the authenticated dropdown

    {#loginHorizontal.html.twig#}
    
    {% trans_default_domain 'FOSUserBundle' %}
    <div class="nav navbar-nav navbar-right">
    <form  class="navbar-form navbar-left form-inline" action="{{ path("fos_user_security_check") }}" method="post" role="form" >
        <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />
        <div class="form-group">
            <div class="input-group">
                <div class="input-group-addon"><i class="fa fa-user" ></i></div>
                <input type="text" class="form-control" id="txt_username"
                       placeholder="{{ 'security.login.username'|trans }}" name="_username"
                       value="{{ last_username }}" required="required" >
            </div>
        </div>
        <div class="form-group">
            <div class="input-group">
                <div class="input-group-addon"><i class="fa fa-asterisk" ></i></div>
                <input type="password"  class="form-control" id="txt_pwd" name="_password" required="required" placeholder="{{ 'security.login.password'|trans }}" />
            </div>
    
        </div>
        <input type="submit" id="_submit" name="_submit"  class="btn btn-primary" value="{{ 'security.login.submit'|trans }}" />
        <br />
        <div class="checkbox">
            <label>
                <input type="checkbox" id="remember_me" name="_remember_me" value="on" /> {{ 'security.login.remember_me'|trans }}
            </label>
        </div>
    </form>
    </div>
    
    
    
    {#authenticadedDropdown.html.twig#}
    
    {% trans_default_domain 'FOSUserBundle' %}
    <ul class="nav navbar-nav navbar-right" >
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown"> welcome, {{ app.user.username }}<span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
                <li><a href="#">bla bla</a></li>
                <li class="divider"></li>
                <li><a href="{{ path('fos_user_security_logout') }}">
                    {{ 'layout.logout'|trans({}, 'FOSUserBundle') }}
                </a></li>
            </ul>
        </li>
        <li></li>
    </ul>
    
  3. Overided the SecurityController and create actions Overide the controller and Created a new Action that renders this template which creates and sends the vars csrf_token & username as parameters for the login.

    namespace Me\UserBundle\Controller;
    
    use FOS\UserBundle\Controller\SecurityController as BaseController;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Security\Core\SecurityContextInterface;
    
    
    class SecurityController extends BaseController
    {
        /**
         * For internal template use: Renders the Horizontal Login ej. Header bar login.
         * No routing used.
         */
        public function loginHorizontalAction(Request $request)
        {
            /** @var $session \Symfony\Component\HttpFoundation\Session\Session */
            $session = $request->getSession();
    
            // last username entered by the user
            $lastUsername = (null === $session) ? '' : $session->get(SecurityContextInterface::LAST_USERNAME);
    
            $csrfToken = $this->container->has('form.csrf_provider')
                ? $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate')
                : null;
    
            $data =  array(
                'last_username' => $lastUsername,
                'csrf_token' => $csrfToken,
            );
            return $this->container->get('templating')->renderResponse('MeUserBundle:Security:loginHorizontal.html.twig', $data);
        }
    
        /**
         * For internal template use: Renders the Dropdown after authentication ej. Header bar for user.
         * No routing used.
         */
        public function authenticatedDropdownAction()
        {
            $data =  array();
            return $this->container->get('templating')
                ->renderResponse('MeUserBundle:Security:authenticatedDropdown.html.twig', $data);
        }
    }
    
  4. Embed controller action Finally I embeded/renderes via the twig template this newly created controller´s action Symfony doc on how to embed controller actions

    <div class="navbar-right" >
        {% block login %}
            {% if is_granted("IS_AUTHENTICATED_REMEMBERED") %}
                {% render(controller("MeUserBundle:Security:authenticatedDropdown")) %}
            {% else %}
                {% render(controller("MeUserBundle:Security:loginHorizontal")) %}
            {% endif %}
        {% endblock %}
    </div>
    

I know it been a while since your post, but hope this helps.

Cheers, Pancho

like image 1
Pancho Avatar answered Oct 22 '22 13:10

Pancho