Laravel csrf token mismatch for ajax GET Request - php

I have an application that is using angular js to make an $http GET request to a server. One page particularly has a form which gets a csrf token embedded into it as follows
<input type="hidden" ng-model="token" value="{{{ Session::getToken() }}}">
In my controller I have the following code:
public function getMethod($arg, $token)
{
/*Check for csrf token validity*/
if ($token != Session::token()) {
return Response::json(
array(),
403
);
}
........
}
From the client side I make a request like this:
var arg = $scope.arg;
var get_url = '/url/routing/to/controller/arg/' + arg + '/' + $scope.token;
$http({method: 'GET', url: get_url})
.success(function(data, status, headers, config) {
//Do stuff after success
.............
})
.error(function(data, status, headers, config) {
//Handle error
.......
});
I am not exactly sure how the GET request can be integrated with csrf tokens but when I make a GET request to the registered URL, I get a token mismatch. Basically a new token is generated every time an ajax request is sent to the server, therefore the initial token extracted in the form input element does not match when I am comparing it in the controller. Could anyone tell me how csrf validity can be done in this case?
Thanks

You should not be adding/modifying resources through GET, therefore you do not need a token on a get request. CSRF tokens are needed only in methods that change or add resources to your application using the currently logged in user's credentials.

Related

Why I cant initialize a Channel using Vue?

I am having trouble when I'm trying to initialise a Channel.
I've followed some tutorials provided (https://getstream.io/blog/chat-messaging-with-laravel/, https://getstream.io/blog/tutorial-build-customer-support-chat-with-laravel-vue-and-stream/) that have a stack as mine (Laravel + Vue)
I am already getting the token on the backend, initializing the Client, setting the User and the token on the client.
But when I try to do this.channel.watch(); or even a simple channels query like
const filter = { type: 'messages', id: '1000056864'};
const sort = { last_message_at: -1 };
const channels = await this.client.queryChannels(filter, sort, {
watch: true,
state: true,
});
It will return to me the error as follows:
Access to XMLHttpRequest at 'https://chat-us-east-1.stream-io-api.com/channels/messages/1000056864/query?user_id=62&api_key=2e******e2&connection_id=5983f850-3d50-4ac3-9c06-d9e0fdaf7212' from origin 'http://local.site.test' has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
Everything is working on the backend, even the equivalent calls.
Based on the error you are receiving, it looks like you are including your CSRF token to all your AJAX requests. Stream API servers have a whitelist of headers that you can pass, this is to safe developers from sending sensitive data by accident. In this specific case it is arguable that csrf-token could be in such whitelist for the sake of ease of use.
Perhaps you are using something like this on your frontend?
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If that's the case my suggestion is to opt for a more fine grained solution such as:
$.ajaxSetup({
url: "/laravel/",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Or make sure that only your Laravel backend receives the CSRF token by extracting JS code doing Ajax calls.
CSRF tokens are not as valuable as session IDs but they exist to make your application more secure and are not meant to be shared with 3rd parties.

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.

JQuery AJAX is encoding API Token for Laravel Application, results in 401 Unauthorized

I have a small application and it has one route that returns JSON. If I use Postman or my browser, I get the correct result. Similarly, if I am running a server on my computer, I get the correct result.
On a live server, however, jQuery is encoding the api token before submitting it, and I'm not getting the result, just a 401 error.
let product_id = $(this).val()
let token = $('input[name=token]').val()
$.ajax({
url: 'api/campaign/',
data: {
'product_id': product_id,
'api_token': token,
},
success: function (data) {
// Do Stuff
}
})

JQuery AJAX cross-site request under Laravel CSRF protection

I'm building a CMS-like web application using Laravel(back-end) and ReactJS with JQuery(front-end).
I decide to put the existing Web API into a separate domain(api.test.com), and my user interface is on the different domain(test.com).
On test.com, I launch an ajax request to api.test.com to modify some resource on the server:
$.ajax({
url: "api.test.com",
method: 'POST',
data: {...}
success: function (no) {
// ...
}
});
And of course it's illegal due to 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 is solved perfectly but another problem occurs due to Laravel's CSRF protection...
Laravel requires a CSRF token included in the request(POST,PUT...which will modify the resource) by default.
In my case, I must generate csrf_token on api.test.com rather than test.com because different domain do not share the token.
I followed the User Guide of Laravel and added these code to my front-end:
$.ajax({
url: "api.test.com/token", // simply return csrf_token();
method: "GET",
success: function (token) {
// Now I get the token
_token = token;
}.bind(this)
});
and modify the previous request implementation:
$.ajax({
url: "api.test.com",
method: 'POST',
headers: {
"X-CSRF-TOKEN": _token // Here I passed the token
},
data: {...}
success: function (no) {
// ...
}
});
But Laravel responses a status code of 500. Then I checked the 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);
}
The $token which I 'POST' to is different from what it was ($request->session()->token()).
I found that the validation tokens on server are different when calling $.ajax.
I try to put the two requests in the same session(by changing the cookie), but it's impossible.
I spent a lot of time to solve this problem but didn't work it out.
Have any idea or solution?
Thanks,
Micooz
Thank you for answering my question. I've considered disabling the CSRF protection to some URIs but I don't want to take these risk.
The key point of my question is that the $.ajax forgets carrying cookies before request, and resulting token validation failed.
Now I setup the JQuery Ajax, let it carry cookies before make a request.
$.ajaxSetup({
xhrFields: { withCredentials: true }
});
and Nginx conf:
add_header Access-Control-Allow-Credentials true;
BTW, it's not necessary to include the token in the data:{}(Form).
All the problems are settled and it works perfectly for me.
Laravel expects the token as a data variable, included on your fields, the name of the var needs to be _token try to change it.
Another solution is including the token in your data not in the headers.
$.ajax({
url: "api.test.com",
method: 'POST',
data: { _token : _token }
success: function (no) {
// ...
}
});
You can follow this url
http://laravel.io/forum/11-14-2014-disabling-the-csrf-middleware-in-laravel-5
In this link, you need to wrap up VerifyCsrfToken class with new one class where you specify actions on which you want not use csrf_token

Pyrocms post request 505 error?

Using PyroCMS, I send a POST request that returns a HTTP 505. If I send GET request on same url is is working.
This is my route file code.
$route['admin/pms(/:any)?'] = 'admin$1';
This is url i send.
http://domain.com/index.php/admin/pms/index/2?
Why doesn't POST work?
You have to include the CSRF hash name in your POST request:
$.post(
SITE_URL + 'module/controller/function',
{
data: data,
otherdata: somemoredata,
csrf_hash_name: $.cookie('csrf_cookie_name')
},
function() { console.log('Yay'); }
);
Check out system/cms/config.php, setting $config['csrf_cookie_name'], to see what your cookie name is. 'csrf_cookie_name' is the default.
Other "solution" would be to turn off CSRF protection.

Categories