JQuery AJAX cross site request in Laravel CSRF protection

I am creating a CMS-like web application using Laravel (back-end) and ReactJS with jQuery (front-end).

I decided to host the existing web API in a separate domain (api.test.com), and my user interface is in a different domain (test.com).

In test.com, I run an ajax request on api.test.com to change some resource on the server:

  $.ajax({
    url: "api.test.com",
    method: 'POST',
    data: {...}
    success: function (no) {
    // ...
    }
  });

And of course, this is illegal due to a security problem. However, I can configure my web server:

For Nginx:

  add_header Access-Control-Allow-Origin http://test.com;
  add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;
  add_header Access-Control-Allow-Headers X-Requested-With,X-CSRF-TOKEN,X-XSRF-TOKEN;

The Access-Control-Allow-Origin problem has been resolved, but another problem arises due to Laravel CSRF protection ...

Laravel requires the CSRF token included in the request (POST, PUT ... which will change the resource) by default.

csrf_token api.test.com, test.com, .

Laravel :

  $.ajax({
    url: "api.test.com/token", // simply return csrf_token();
    method: "GET",
    success: function (token) {
      // Now I get the token
      _token = token;
    }.bind(this)
  });

:

  $.ajax({
    url: "api.test.com",
    method: 'POST',
    headers: {
      "X-CSRF-TOKEN": _token // Here I passed the token
    },
    data: {...}
    success: function (no) {
    // ...
    }
  });

Laravel 500. VerifyCsrfToken.php:

protected function tokensMatch($request)
{
    $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
    if (!$token && $header = $request->header('X-XSRF-TOKEN')) {
        $token = $this->encrypter->decrypt($header);
    }
    // Log::info($request->session()->token() . " == $token");
    return Str::equals($request->session()->token(), $token);
}

$, << → POST ' , ($request- > session() → token()).

, $.ajax.

( cookie), .

, , .

?

, Micooz

+4
3

, . CSRF URI, .

, $.ajax cookie .

JQuery Ajax, cookie, .

  $.ajaxSetup({
    xhrFields: { withCredentials: true }
  });

Nginx conf:

  add_header Access-Control-Allow-Credentials true;

, : {} ().

, .

+3

Laravel , , var _token .

, .

  $.ajax({
    url: "api.test.com",
    method: 'POST',
    data: { _token : _token }
    success: function (no) {
    // ...
    }
  });
0

URL

http://laravel.io/forum/11-14-2014-disabling-the-csrf-middleware-in-laravel-5

In this link, you need to wrap the class with a VerifyCsrfTokennew class, which indicates actions for which you do not want to use csrf_token

-1
source

Source: https://habr.com/ru/post/1598242/


All Articles