11

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

2 Answers 2

45

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') }}" />
4
  • 3
    This should be marked as the best answer - cleaner and easier than the other one. Commented Nov 25, 2014 at 6:28
  • This is the best and cleanest solution. Render controller in templates consume a lot of resources: this solution is the best and cleanest one.
    – Aerendir
    Commented Feb 27, 2015 at 13:27
  • Is this the same for Symfony 3.2? Commented Apr 7, 2017 at 16:04
  • @RodolVelasco "Symfony 2.4 and later:" - try it, not much code
    – James
    Commented May 23, 2019 at 14:27
6

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.