Well, having spent a lot of time reading the FOSUserBundle code, and especially the registration controller and the factory form, I came up with a fully working solution.
Before doing anything, be sure to disable CSRF in your symfony2 configuration.
Here is the controller that I use to register:
public function postUserAction(\Symfony\Component\HttpFoundation\Request $request) { $formFactory = $this->get('fos_user.registration.form.factory'); $userManager = $this->get('fos_user.user_manager'); $dispatcher = $this->get('event_dispatcher'); $user = $userManager->createUser(); $user->setEnabled(true); $event = new \FOS\UserBundle\Event\GetResponseUserEvent($user, $request); $dispatcher->dispatch(\FOS\UserBundle\FOSUserEvents::REGISTRATION_INITIALIZE, $event); if (null !== $event->getResponse()) { return $event->getResponse(); } $form = $formFactory->createForm(); $form->setData($user); $form->handleRequest($request); if ($form->isValid()) { $event = new \FOS\UserBundle\Event\FormEvent($form, $request); $dispatcher->dispatch(\FOS\UserBundle\FOSUserEvents::REGISTRATION_SUCCESS, $event); $userManager->updateUser($user); if (null === $response = $event->getResponse()) { $url = $this->generateUrl('fos_user_registration_confirmed'); $response = new \Symfony\Component\HttpFoundation\RedirectResponse($url); } $dispatcher->dispatch(\FOS\UserBundle\FOSUserEvents::REGISTRATION_COMPLETED, new \FOS\UserBundle\Event\FilterUserResponseEvent($user, $request, $response)); $view = $this->view(array('token' => $this->get("lexik_jwt_authentication.jwt_manager")->create($user)), Codes::HTTP_CREATED); return $this->handleView($view); } $view = $this->view($form, Codes::HTTP_BAD_REQUEST); return $this->handleView($view); }
Now the tricky part was representing the form using REST. The problem was that when I sent JSON, like this one:
{ "email":" xxxxx@xxxx.com ", "username":"xxx", "plainPassword":{ "first":"xxx", "second":"xxx" } }
The API responded like nothing was sent.
The solution is that Symfony2 is waiting for you to encapsulate form data in the form name!
Question: "I did not create this form, so I do not know what its name is." So I again went to the package code and found out that the form type was fos_user_registration, and the getName function returned fos_user_registration_form.
As a result, I tried to present my JSON in this way:
{"fos_user_registration_form":{ "email":" xxxxxx@xxxxxxx.com ", "username":"xxxxxx", "plainPassword":{ "first":"xxxxx", "second":"xxxxx" } }}
And voila! it worked. If you are trying to set up your fosuserbundle using fosrestbundle and LexikJWTAuthenticationBundle, just ask me, I will be happy to help.