Search code examples
symfonysilex

Silex 2/Symfony: Check CSRF token from security login form


I do not use the "Form Service Provider" and manually output the CSRF token to my twig login form:

$csrf_token = $app['csrf.token_manager']->getToken('token_id'); //'TOKEN'

And in the login.html.twig:

<input type="hidden" name="_csrf_token" value="{{ csrf_token }}">

The manual (https://silex.symfony.com/doc/2.0/providers/csrf.html) says, that it's possible to check the token like this:

$app['csrf.token_manager']->isTokenValid(new CsrfToken('token_id', 'TOKEN'));

But the whole login process is handled by the security component. How do I add the CSRF check to it?

This is my firewall setup:

$app['security.firewalls'] = array(
'login' => array(
    'pattern' => '^/user/login$',
),
'secured_area' => array(
    'pattern' => '^.*$',
    'anonymous' => false,
    'remember_me' => array(),
    'form' => array(
        'login_path' => '/user/login',
        'check_path' => '/user/login_check',
    ),
    'logout' => array(
        'logout_path' => '/user/logout',
        'invalidate_session' => true
    ),
    'users' => function () use ($app) {
        return new UserProvider($app['db']);
    },
));

And the Login controller:

$app->get('/user/login', function(Request $request) use ($app) {
   $csrf_token = $app['csrf.token_manager']->getToken('token_id'); //'TOKEN'

    return $app['twig']->render('login.html.twig', array(
        'csrf_token' => $csrf_token,
    ));
});

Solution

  • Try to add csrf options to security config:

    $app['security.firewalls'] = array(
    ....
        'form' => array(
            'login_path' => '/user/login',
            'check_path' => '/user/login_check',
            'with_csrf' => true,
            'csrf_parameter' => '_csrf_token', // form field name
            'csrf_token_id' => 'token_id'
        ),
    ....