Pregunta

I'm new working with symfony2 and I have a problem when I try to validate the csrf token in a custom form, my question is ¿how can I validate the csrf token in the controller?

This is my code in my view.

<form role="form" action="{{ path('default_select_city_check') }}" method="post">
       <input type="hidden" name="_csrf_token" value="{{ csrf_token('default_select_city_check') }}">
            ...
        </form>

This is my code in the controller:

public function selectCityCheckAction(Request $request) {
    // in this part, how can I compare the token value in the form with the token value in the session?
}

Thank you for your help

¿Fue útil?

Solución

add a function in your controller:

 public function isCsrfTokenValid($intention, $token_name = '_csrf_token')
 {
    return $this->get('form.csrf_provider')
        ->isCsrfTokenValid($intention, $this->getRequest()->get($token_name));
 }

in your Action:

if ($this->isCsrfTokenValid('default_select_city_check')) {
   //do something you want
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top