Symfony FOSUserBundle - include login form in layout template

本秂侑毒 提交于 2019-11-27 12:45:53

问题


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


回答1:


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;



回答2:


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') }}" />


来源:https://stackoverflow.com/questions/10903114/symfony-fosuserbundle-include-login-form-in-layout-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!