Remove some cookie from ajax call with Axios - ajax

I use Axios in browser to call ajax request. Now I have a problem with some cookie that has high priority than some header. Per request I send a header as AUTHTOKEN but in cookie SESSIONID key stored that high priority than AUTHTOKEN header. In some scenario, I need to ignore cookie. This is my code:
axios({
url:`${sdpBasicUrl}/api/v3/requests/27363`,
method: 'get',
headers: {
'Content-Type': 'application/json'
'AUTHTOKEN': 'GHG23847923HGJ'
}
})
.then(res => {
console.log(res.data);
});
and this is cookie sample:
_z_identity=true; PORTALID=1; csrfcookie=aasdasdjh24234b2bjh4hjl; SESSIONID=ffd68d32a14841c99905e3cf4897e15ec9b4777020854a76821fd7e1eab6db2dcab482eb4cfea2ce7f5a6c47c80271d09f608ed985004e5c85681b2939681b18
What should I do? Do you have any solution to solve my problem?

You are able to pass in cookies through the header like this:
Axios.request({
url: "http://example.com",
method: "get",
headers:{
Cookie: "cookie1=value; cookie2=value; cookie3=value;"
}
}).then...
So if you don't want the value to be there, you could override the values.
https://github.com/axios/axios/issues/943

You can use transformRequest to modify the header for some requests. transformRequest allows changes to the request data and header before it is sent to the server. This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'.
transformRequest: [function (data, headers) {
// Modify the header here and return the header
return data;
}],
You can get more information about it on https://axios-http.com/docs/req_config

Related

Symfony 3, "ajax request" with fetch API, and CSRF

In twig i generate a csrf token ({{ csrf_token('my_intention') }}).
In Javascript i call a controller with ajax, in fact with the Fetch API (Ajax xmlHttpRequest tried too), POST request. Argument name containing the token passed in the request is 'token=abcdef...'.
AJAX:
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {
console.log(data);
};
httpRequest.open('POST', el.getAttribute("data-url"));
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(.......);
Fetch API:
fetch(el.getAttribute('data-url'), {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'token=' + encodeURIComponent(el.getAttribute('data-token'))
}).then(data => data.text()).then(data => {...}
In the controller action called i get the token sent as data from the POST request. I check the token like this in the controller:
$token = $request->request->get('token');
if (!$this->isCsrfTokenValid('my_intention', $token)) {
throw new InvalidCsrfTokenException("error csrf 2");
}
But Symfony say the token is not valid.
I'm not sure but i think token is not found in session variable. In isTokenValid() $this->storage->hasToken($token->getId()) return false.
In the browser, if i call the url directly, it's ok.
In twig i set the url to call in a data attribute like this data-url="{{ path('_check', {'id': transaction.id}) }}", then i read this data attribute from javascript and pass it to ajax/fetch function.
I tried ajax with jQuery $.post(... and it works. The only difference is Cookie:PHPSESSID... in the request header with jQuery not on my original code.
I don't understand, what is wrong with my code ?
Symfony 3.1.3
EDIT: resolved: i didn't pass credentials in headers request, so, no way for Symfony to find session and check token:
fetch(el.getAttribute('data-url'), {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest"
},
body: 'token=' + el.getAttribute('data-token'),
credentials: 'include'
}).then(data => data.text()).then(data => {
Even if you found an answer to your issue, I recommend you to take a look at this bundle which handles the token verification based on a Cookie which is defined server-side and that you should pass in each asynchronous request.
https://github.com/dunglas/DunglasAngularCsrfBundle

How to access angular $http response custom headers?

Here is my code:
$http({
method: 'POST',
url: myURL,
headers: {
//BLAH
},
data: {
// BLAH BLAH
}
}).success(function(data, status, headers) {
deferred.resolve({
// This is not possible:
sessionId: headers('sessionId')
});
});
I would like to access sessionId attribute from headers, but only header I seem to find is Content-Type.
What may be the cause why this does not work?
I found this post useful: https://github.com/mgonto/restangular/issues/128
It states the following:
After research I found the solution: you have to tell your api server to "expose" the custom headers. You can do this by using the Access-Control-Expose-Headers header. The value is the headers you want to be able to access. So it'd look like: Access-Control-Expose-Headers: Your-Header, Another-Header.
Adding this extra header solved my problem.

AngularJS CORS Web API Call

I am trying to make a request to the Eventbrite API. I can successfully make a call from Postman (chrome extension similar to fiddler)
url: https://www.eventbriteapi.com/v3/users/me/owned_events
Header: authentication : Bearer Y5R3SQRPRZBULIHYQHTD
This successfully gets back what I'm looking for. When I try to make the same call through AngularJS
function getLiveEvents() {
return $http.get(url, {
cache: true,
headers: {
'Authorization': 'Bearer Y5R3SQRPRZBULIHYQHTD',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*',
}
}).then(function (response) {
return response.data;
});
}
I always get the error XMLHttpRequest cannot load https://www.eventbriteapi.com/v3/users/me/owned_events?status=live. The request was redirected to 'https://www.eventbriteapi.com/v3/users/me/owned_events/?status=live', which is disallowed for cross-origin requests that require preflight.
Is there something I can do with my AngularJS request so that it will be successful?
FYI: The access-token is real, I'm not concerned about someone using it because it's just a test account.

Can't retrieve my x-api-key from my request header with CORS enabled. Why?

I'm working with CodeIgniter2 Rest API and AJAX to make requests from a smartphone with PhoneGap to a AWS server with apache.
Everything was working fine when working on my localhost/browser.
But when trying to set up a distant server things got bad.
I have configured my server properly with CORS so that it allows external requests as explained here :
http://dev.nuclearrooster.com/2011/01/03/cors-with-apache-mod_headers-and-htaccess/
To secure the API, I have been setting up an API KEY that I have to pass in the header of my request like so:
$.ajax({
type:"GET",
url: server_url + 'user/available',
headers: { 'X-API-KEY': key },
dataType: 'json'
});
But then, after seeing my ajax called being refused because of an invalid API Key, I have been trying to make sure the server received the key. and it doesnt. when I try to echo my key, its empty.
I can see in my debug console the following:
Request header field X-API-KEY is not allowed by Access-Control-Allow-Headers.
So I have been modifying my .htaccess following this post:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, x-api-key"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
so now, the message is gone but the problem still remains the same ... why ?
How can I transmit this X-API-KEY through my AJAX call Header so I can authentificate my users ?
Many Thanks
I faced this problem and with weeks of tweaking I was able to get it to work with a hack of a job... I can't remember the exact part that did fix it but will provide with what I am currently using.
Server Side
function __construct(){
parent::__construct();
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Headers: X-API-KEY");
}
function available_options(){
$this->response(array('response' => array()), 200);
}
Client Side
function sendData(dataToSend, successCallback) {
window.default_headers['X-API-KEY'] = '_KEY_';
return $.ajax({
type: "POST",
url: server_url + 'user/available',
data: { data : JSON.stringify(dataToSend) }, // serializes the form's elements.
dataType: 'json',
headers: window.default_headers,
xhrFields: {
withCredentials: true
}
});
}
Since you're using a GET request, possibly using JSONP would be of more use, this avoids cross domain requests.
JSONP Request
$.ajax({
type : "GET",
dataType : "jsonp",
url: server_url + "user/available?callback=?", // ?callback=?
success: function(data){
// do stuff with data
}
});

Sencha Touch Ajax Request Error: Origin null is not allowed by Access-Control-Allow-Origin.

I am making an Ajax request to remote server and sending parameters as POST method.
But I am getting following response:
**"MLHttpRequest cannot load http://rasovai.com/mobilecontact1.php?_dc=1369189135731. Origin null is not allowed by Access-Control-Allow-Origin. "**
I read about this error and found out that it is because of CORS, so I add header to the request as follows:
Ext.Ajax.defaultHeaders = {
'Accept': 'application/json',
'Accept': 'Access-Control-Allow-Origin: *',
'Accept': 'Access-Control-Allow-Credentials: true',
'Accept': 'Access-Control-Allow-Methods: OPTIONS, GET, POST',
'Accept': 'Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control'
};
but still I am getting the same error in response.
I am able to hit the url on server, but not able to pass the parameters.
Can anyone help me in this regard?
Thanks
Ishan jain
Those headers need to be sent by the server, not the client.
If you are using Chrome browser you can use --disable-web-security flag to allow cross domain requests and if you are building this into app this will work fine. Have a look at this thread for more details : How to use json proxy to access remote services during development
If you want to pass the params to the server then you can do it as following.
Ext.Ajax.request({
url : serverURL,
jsonData : requestParams, // Object which encapsulates the request params
method : 'POST',
withCredentials: true,
useDefaultXhrHeader: false,
// List of header params can be sent as follows
headers : {
"Content-Type" : "application/json",
"Accept" : "application/json",
"Access-Control-Allow-Origin":"http://localhost:8080",
"Authorization":auth
},
username : 'mobiliser',
password : 'secret',
success : function(response) {
}
failure : function ()
{
}
As you said in your question that, the server is on a different domain, you may have to use JSONP request.
Let me know if you have any questions.
Thanks-
Gendaful

Resources