Adding Captcha to Symfony2 Login Page

Adding Captcha to Symfony2 Login Page

I am not sure this is a great idea. But it’s doable.

Where is the symfony or FOSUserBundle login form type?

There is no form type for the login. The form is directly embed in the template as you can see in login.html.twig.

How could you do it?

You could totally create one but you would have to customize the SecurityController so that you send your form to the template.


The procedure would be something like that:

1. Create your custom loginFormType (that’s where you can add your captcha in the builder).

2. Override the SecurityController (you could take a look here to see something similar). You need to override the loginAction method so that you can pass the form to your template here.

3. Override login.html.twig to render the form passed from your controller


Edit: Answer to your comment

How can you access to your form in a controller that extends
ContainerAware?

I highly recommend this reading to see how you can move away from the base controller. Now, how can you do this?

Well, you have 2 options:

OPTION 1: EASY WAY

$form = $this->createForm(new LoginFormType(), null);

becomes:

$form = $this->get('form.factory')->create(new LoginFormType(), $null);

OPTION 2: REGISTER FORM AS A SERVICE

1. Create your formType (normal procedure): loginFormType

2. Define your form as a service acme_user.login.form. You have a great example here (In the 1.2 version of FOSUserBundle, both registration and profile forms were registered as services, so this gives you a perfect example of how it’s done).

3. You can now use your form inside your controller extending ContainerAware. See here.

$form = $this->container->get('acme_user.login.form');

Leave a Comment