【问题标题】:FOSUserBundle & REST Api Call: How to use custom FormType?FOSUserBundle & REST Api 调用:如何使用自定义 FormType?
【发布时间】:2014-04-17 11:59:40
【问题描述】:

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

我已经覆盖了 FOSUserBundle 的 RegistrationController:

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 - 但它正在被调用...

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

【问题讨论】:

  • 您是如何创建自己的 RegistrationFormType 的。您应该覆盖 FOSUserBundle 的 RegistrationFormType。
  • 是的,我的类 ApiRegistrationFormType 正在扩展 FOSUserBundle 的 RegistrationFormType。但它没有捡起来......这条线似乎不起作用: $form = $formFactory->createForm(new ApiRegistrationFormType(), $user);有什么想法吗?

标签: php rest symfony csrf


【解决方案1】:

所以经过大量时间摆弄,我得到了它的工作。我希望它可以节省一些时间。

我使用 FOSRestBundle。

我在我的包中创建了自己的 RestController:

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 中:

registration:
    form:
        type: fos_user_rest_registration

所以基本上我告诉 FOS 用户包使用我自己的注册表单,并根据我是否启用 csrf 令牌的路线...

【讨论】:

  • json对象应该怎么看?我正在发送:{“user”:{“email”:“test@test.pl”,“username”:“koper”,“plainPassword”:“test”}}我的表格仍然无效跨度>
  • 没有用户对象:{ "email":"test@test.pl", "username":"koper", "plainPassword":"test" } 也不起作用
  • 好的,我必须关闭 csrf,但我仍然违反了完整性约束
  • 好吧,如果它违反了完整性约束,这似乎是一个数据库问题。究竟是什么错误信息?
  • 在这里使用表格有什么意义?只是为了验证?不确定,但如果你可以在这里跳过表格,你可以节省很多开销
【解决方案2】:

请简单一点!

假设你同时使用 FOSRestBundleFOSOAuthServerBundle,你正在为已经实现的东西做很多工作......我建议......在你的配置文件中多加 2 行 :)

app/config.yml

# we want to disable csrf roles for users with ROLE_API
fos_rest:
    disable_csrf_role: ROLE_API

# We want to use scope to assign this role when the user requests the token
fos_oauth_server:
        options:
            supported_scopes: user api # https://goo.gl/iE9VoI

瞧!


现在呢?

当您使用范围 api 请求令牌时,您的用户会自动获得角色 ROLE_API,并且 CSRF 约束消失了!

http://YOUR_DOMAIN/oauth/v2/token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECREY&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD&scope=api


是的,它在文档中:

【讨论】:

  • 要进行 oauth 调用,您需要用户名和密码,对吗?你是怎么得到它的?我认为这个问题是关于注册的。一旦你在数据库中有用户名密码,你就可以获得 access_token
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多