简体   繁体   中英

CSRF protection for ajax requests

In laravel documentation , for ajax based applications, there is CSRF protection via HTML meta tag and cheking header request.

Why this method needed and why not check ajax request as usual request? I mean, if for ajax whe use POST method, then send CSRF token as usual parameter (for example as csrf_token ) and then check in server side (PHP) :

if ( !isset($_POST['csrf_token']) OR $_POST['csrf_token'] !== $_SESSION['csrf_token'] ) {
    // incorrect csrf token, stop processing
}

Cheking header request have some advantage than this method ?

If you are doing POST request, CSRF doesn't go through the header it goes through the http message body, what Laravel has is some kind of default middleware for csrf protection, where is the issue in that? If you go into assets/js folder you can see the CSRF token in bootstrap.js.

You can fetch a CSRF token from a global Javascript variable and send it through ajax post request body.

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