Reputation:
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!
Upvotes: 1
Views: 196
Reputation: 738
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!
}
Upvotes: 1
Reputation: 3900
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.
Upvotes: 1