Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony FOSUserBundle - include login form in layout template

Tags:

php

twig

symfony1

We've successfully configured the FOSUserBundle; login, register, reset password, etc, are all working just fine.

Now we want to incorporate the login form into our general site layout, notably placing the form into the top-right section of the layout header. Doing this would be easy enough if we were just dealing with the username and password fields. However we can't seem to figure out how to obtain the CSRF token which is generated by the FOSUserBundle service:

$this->container->get('form.csrf_provider')->generateCsrfToken('authenticate');

I tried calling the above within a Twig extension which otherwise works fine however apparently the extension can't properly reference the container.

Surely there is some easy way to obtain the FOSUserBundle CSRF token globally?

Thanks! Jason

like image 708
Jason Gilmore Avatar asked Jun 05 '12 18:06

Jason Gilmore


2 Answers

Symfony 2.3:

One possible solution would be to define the csrf provider as a Twig global variable like this:

twig:
    globals:
        fos_csrf_provider: "@form.csrf_provider"

And then in your layout call it like this:

<input type="hidden" name="_csrf_token" value="{{ fos_csrf_provider.generateCsrfToken('authenticate') }}" />

So you don't need to call any controller.

Symfony 2.4 and later:

twig:
    globals:
        fos_csrf_provider: "@security.csrf.token_manager"

and:

<input type="hidden" name="_csrf_token" value="{{ fos_csrf_provider.refreshToken('authenticate') }}" />
like image 87
David Morales Avatar answered Nov 12 '22 20:11

David Morales


You can define a function like this in one of your controllers

public function getTokenAction()
{
    return new Response($this->container->get('form.csrf_provider')
                            ->generateCsrfToken('authenticate'));
}

and then just embed it into your form via

<input type="hidden" name="_csrf_token" value="{% render('YourBundle:YourController:getToken') %}" />

You also need to include the following at the top of your controller:

use Symfony\Component\HttpFoundation\Response;
like image 39
Daniel Avatar answered Nov 12 '22 21:11

Daniel