简体   繁体   中英

Symfony 3 csrf token

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!

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.

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!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM