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
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') }}" />
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With