Is there any way that enforce to set CSRF token in login form in symfony

1k Views Asked by At

Obviously, I would like to enforce to set CSRF token in login form. Suppose that I don't add CSRF token in the login form and I've submitted the form. At this point, my request is, the response must be returned as denied so that I didn't add CSRF token.

How can I do this, or Can I do this?

2

There are 2 best solutions below

0
VladRia On

Sure you can. You need simply create and output CSRF token:

<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">

Normally that's all you need because https://github.com/symfony/security/blob/master/Http/Firewall/SimpleFormAuthenticationListener.php#L59-L60 checks the token automatically. You need to put exactly _csrf_token as field name and authenticate as token name.

You cas presonalize it if you want in:

# app/config/security.yml
security:
    # ...

    firewalls:
        secured_area:
            # ...
            form_login:
                # ...
                csrf_parameter: YOUR_csrf_token
                csrf_token_id: YOUR_authenticate

Watch out! This form login listener is deprecated since 4.2. Here is the example with gurad https://symfony.com/doc/current/security/form_login_setup that is recommended to use.

Cheers !

0
rnenciu On

You can inject the CsrfTokenManagerInterface in your Controller and use it in your login method as in the following example:

SecurityController.php

class SecurityController extends Controller
{

    /** @var CsrfTokenManagerInterface */
    private $tokenManager;

    public function __construct(CsrfTokenManagerInterface $tokenManager = null)
    {
        $this->tokenManager = $tokenManager;
    }

    /**
    * @Route("/login", name="login")
    *
    * @param Request $request
    */
    public function login(Request $request)
    {
        // Get the login error if exists
        $error = $this->get('security.authentication_utils')->getLastAuthenticationError();

        // Last username entered by user
        $lastUsername = $this->get('security.authentication_utils')->getLastUsername();

        $csrfToken = $this->tokenManager
            ? $this->tokenManager->getToken('authenticate')->getValue()
            : null;

        if (null === $csrfToken) {
            //your exception
        }

        return $this->renderLogin([
            'last_username' => $lastUsername,
            'error' => $error,
            'csrf_token' => $csrfToken
        ]);
    }
}