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",
method: "GET",
success: function (token) {
_token = token;
}.bind(this)
});
:
$.ajax({
url: "api.test.com",
method: 'POST',
headers: {
"X-CSRF-TOKEN": _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);
}
return Str::equals($request->session()->token(), $token);
}
$, << → POST ' , ($request- > session() → token()).
, $.ajax.
( cookie), .
, , .
?
,
Micooz