FOSUserBundle& REST Api调用:如何使用自定义FormType? [英] FOSUserBundle & REST Api Call: How to use custom FormType?

查看:47
本文介绍了FOSUserBundle& REST Api调用:如何使用自定义FormType?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Symfony2网站上使用FOSUserBundle。现在,我正在开发一个API,以允许通过REST api调用进行注册。

I am using FOSUserBundle on my Symfony2 Website. Now I am working on an API to allow registration over a REST api call.

我已覆盖FOSUserBundle的RegistrationController:

I have overridden the RegistrationController of FOSUserBundle:

ApiRegistrationController.php:

 /**
 * @Route("/user/", defaults = { "_format" = "json" }, requirements = { "_method" = "POST" })
 * 
 */
public function registerAction(Request $request)
{
    [...]

    $form = $formFactory->createForm(new ApiRegistrationFormType(), $user);

    [...]
}

ApiRegistrationFormType.php:

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'BenMarten\UserBundle\Entity\User',
        'intention'  => 'registration',
        'csrf_protection' => false
    ));
}

我收到有关错误CSRF令牌的错误,所以我创建了自己的RegistrationFormType ,以禁用CSRF-但它被称为...

I get the error about the wrong CSRF token, so I created my own RegistrationFormType, to disable CSRF - but it is into being called...

如何实现仅针对api调用禁用CSRF令牌?

How can I achieve disabling the CSRF token only for the api calls?

推荐答案

因此,经过很多时间的摆弄之后,我开始使用它了。我希望它可以节省一些时间。

So after a lot of time fiddling around, I got it working. I hope it saves someone some time.

我使用FOSRestBundle。

I use FOSRestBundle.

我在自己的计算机上创建了自己的RestController捆绑包:

I have created my own RestController in my bundle:

RestController.php

namespace BenMarten\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;

/**
 * Rest Controller
 */
class RestController extends Controller
{
    /**
     * Create a new resource
     *
     * @param Request $request
     * @return View view instance
     *
     */
    public function postUserAction(Request $request)
    {
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->container->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->container->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');

        $user = $userManager->createUser();
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $formFactory->createForm();
        $form->setData($user);

        $jsonData = json_decode($request->getContent(), true); // "true" to get an associative array

        if ('POST' === $request->getMethod()) {
            $form->bind($jsonData);

            if ($form->isValid()) {
                $event = new FormEvent($form, $request);
                $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

                $userManager->updateUser($user);

                $response = new Response("User created.", 201);               

                return $response;
            }
        }

        $view = View::create($form, 400);
        return $this->get('fos_rest.view_handler')->handle($view);
    }
}

RestRegistrationFormType.php

namespace BenMarten\UserBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\DependencyInjection\Container;

class RestRegistrationFormType extends AbstractType
{
    protected $routeName;
    private $class;

    /**
     * @param string $class The User class name
     */
    public function __construct(Container $container, $class)
    {
        $request = $container->get('request');
        $this->routeName = $request->get('_route');
        $this->class = $class;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($this->routeName != "post_user")
        {
            $builder
                ->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
                ->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
                ->add('plainPassword', 'repeated', array(
                    'type' => 'password',
                    'options' => array('translation_domain' => 'FOSUserBundle'),
                    'first_options' => array('label' => 'form.password'),
                    'second_options' => array('label' => 'form.password_confirmation'),
                    'invalid_message' => 'fos_user.password.mismatch',
                ))
            ;
        }
        else
        {
            $builder
                ->add('email', 'email')
                ->add('username', null)
                ->add('plainPassword', 'password')
            ;        
        }
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        if ($this->routeName != "post_user")
        {
            $resolver->setDefaults(array(
                'data_class' => $this->class,
                'intention'  => 'registration',
            ));
        }
        else
        {
            $resolver->setDefaults(array(
                'data_class' => $this->class,
                'intention'  => 'registration',
                'csrf_protection' => false
            ));            
        }
    }

    public function getName()
    {
        return 'fos_user_rest_registration';
    }
}

已将服务添加到Services.xml:

<service id="ben_marten.rest_registration.form.type" class="BenMarten\UserBundle\Form\RestRegistrationFormType">
        <tag name="form.type" alias="fos_user_rest_registration" />
        <argument type="service" id="service_container" />
        <argument>BenMarten\UserBundle\Entity\User</argument>
    </service>

在config.yml中:

And in config.yml:

registration:
    form:
        type: fos_user_rest_registration

所以基本上我告诉FOS用户捆绑包使用我自己的注册表格,并根据路线启用或不启用csrf令牌...

So basically I tell the FOS user bundle to use my own registration form and depending on the route i enable the csrf token or not...

这篇关于FOSUserBundle&amp; REST Api调用:如何使用自定义FormType?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆