1

How can I get or set the csrf_token with symfony? here my code and I don't know how can I do with csrf_token,

$username = $request->request->get('username');
$password = $request->request->get('password');

    if($request->isMethod('POST')){
        $headers = array('Accept' => 'application/json');
        $query = array('email' => $username, 'mdp' => $password);

        $url = ' /**/ ';
        $body = Unirest\Request\Body::json($query);

        $response = Unirest\Request::post('$url',$headers,$body);

        return new Response(json_encode($response));

    }

    return $this->render('AppBundle:Default:index.html.twig');

Thanks!

2
  • Did you read the doc? What your form does look like? Commented Oct 27, 2017 at 7:59
  • Did you tried ? Commented Nov 4, 2017 at 6:28

2 Answers 2

1

Symfony doesn't provide a CSRF token to every POST request by default. My recommendation would be to use Symfony Forms that give you CSRF protection out of the box. This will also make your life easier when handling form submission, adding validation rules, rendering the form, and much more.

Sign up to request clarification or add additional context in comments.

Comments

1

Bartosz answer is a possibility. But if you don't want to use a Symfony form you can do in your twig template:

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

In your controller:

$csrfTtoken =  $request->request->get('_csrf_token');
if ($this->isCsrfTokenValid('my_form', $csrfTtoken)) {
    // csrf token is valid!
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.