How to disable Caching in CORS-Anywhere? - javascript

I am running into CSRF token validation failed error when trying to do a POST request on an endpoint which is on a different server using cors-anywhere. Its mostly because the CSRF Token that I am passing to the cors-server is cached and hence the validation fails.
I have read the following Stack Overflow link - Similar issue
. Turns out my problem is same as the one in the link but since that link does not contain any solution I am asking it here.
Please help.
EDIT:-
$.ajax({
async: false,
crossDomain: true,
data: batch_request,
url: "https://cors-anywhere.herokuapp.com/https://......api.s4hana.ondemand.com:xxx/sap/opu/odata/sap/API_MKT_CONTACT_SRV;v=0002/$batch",
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxxx");
xhr.setRequestHeader("X-CSRF-Token", "xxxxxxxxx");
xhr.setRequestHeader("Content-Type", "multipart/mixed;boundary=batch");
},
success:function(response) {
console.log("Succesfully added new contacts");
console.log(response);
},
error: function (error) {
console.log("Error");
console.log(error);
}
});
I have made a GET call using POSTMAN and retrieved the CSRF token from the server. For now, I have hardcoded the token in the AJAX call. I receive the following error when I do it-

CSRF validation depends on matching two tokens associated with the request. Typically one is in the request itself and the other is stored in a session associated with the request by a cookie.
Since you are going through a simple proxy, you are anonymising yourself and there is no session associated with the request.
If you want to work around this, then you would need to write your own server-side proxy which maintained the session on a per-user basis.

Related

POST data to a Google form with AJAX

I am trying to post data to a from AJAX to a Google form, but even though it reports success with a statusCode of 0, the data never appears in the form:
var dat={ "entry.529474552" :"data1", "entry.1066559787": "name1"};
postToGoogle("1FAIpQLSf4w1OQGsIncaiqXlmfAl4jYSt-e4Zx3xVJa7Weob4LnQbRZQ",dat);
function postToGoogle(id, dat) {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', 'chrome-extension://EXTENSION_ID');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
},
url: "https://docs.google.com/forms/d/e/"+id+"/formResponse",
data: dat,
type: "POST",
dataType: "xml",
xhrFields: { withCredentials: true },
statusCode: {
0: function() { console.log("OK") },
200: function() { console.log("error") },
}
});
}
It generates a CORS error, but supposedly, the POST should go through anyway.
For those looking to do this as of April 2019
I was working on this today. The current answer is as follows:
Each field in the Google Form has a unique ID. In order to retrieve it, get a pre-filled link by filling out all relevant form fields you wish to programatically submit
Note: In order to ensure the URL is accessible without restriction, you'll also want to disable restriction to your domain only (for GSuite paying users)
Then, copy the link and paste in your browser. The URL has a base format as follows:
https://docs.google.com/forms/d/e/[FORMID]/formResponse
Each param is a key/value pair of type: entry.XXXXXX=value
The prefilled link will give you the value of XXXXX for each relevant field
Request must be made with following headers:
Method: GET
Content-Type: application/x-www-form-urlencoded
The final request looks like this
https://docs.google.com/forms/d/e/123332233bsj333/formResponse?entry.123456=value1&entry.2333442=value2&submit=Submit
Don't forget to append submit=Submit at the end of your request!
It generates a CORS error, but supposedly, the POST should go through anyway.
While it is possible to make a successful POST request, get a CORS error, and be unable to read the response, this is only true for Simple Requests.
Because your request has:
Custom headers (Access-Control-Allow-Origin and Access-Control-Allow-Methods, which are response headers and have no business being on a request in the first place)
Credentials (i.e. you have set withCredentials: true)
… it is a Preflighted Request.
Before the browser will make the POST request, it will make an OPTIONS request to ask permission.
Since it doesn't get permission, the request fails.
Note that even if you did turn it into a simple request and make the POST successfully, you would still get a status of 0. You can't read the status when there is a CORS error.

jQuery AJAX call sending as OPTIONS and missing Authorization header

I'm starting to get stumped on this. I'm developing a C#.NET Web API service and frontend application to use it. I've been having a lot of difficulty using a token to authenticate my requests and jQuery seems to be having trouble. I can get a token just fine, but jQuery won't add it to an Authorization header in further requests.
My setup is an index.html page with several jQuery Mobile pages inside it. It starts on a '#login' page, which sends a request to my /Token URI with a username, password, and grant type. This is successful and the return is the token. The page changes to '#home' and a test ajax call is sent to /api/values to grab value. The problem is that instead of adding a header called 'Authorization', jQuery adds an 'Access-Control-Request-Headers' with the value 'accept, authorization' instead. At first I thought it was a CORS issue, but the request works fine when I use Advanced Rest Client in Chrome to send the request.
AJAX Call from '#Home'
$.ajax({
url: 'http://slalomtest2.azurewebsites.net/api/values/',
type: 'GET',
async: true,
dataType:"json",
beforeSend: function(request){
request.withCredentials = true;
request.setRequestHeader("Authorization", "Basic " + Token);
},
success: function(result){
console.log(result);
},
error: function(request, error){
$.mobile.changePage("#login");
}
});
The bad request the AJAX sends
This is what it looks like from Advanced Rest Client in the same browser
Thanks in advance for the help, I've been banging my head against the wall all day.

Salesforce OAuth with REST API using Javascript

I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.
Step 1) I request access token using username and password via the below code snippet
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username#location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
My request, however, is failing with the following message:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
I have seen some sources (here here here) mention that CORS is not supported in salesforce, and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.
In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to login users and access their salesforce data from my connected app?
All and any help is appreciated!
You will need to handle the OAUTH part on your own server. This isn't just due to lack of CORS, there is also no way to securely OAUTH purely on the client-side. The server could really be anything but here is an example server written in Java using Play Framework which has a JavaScript / AngularJS client as well: http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
You can not make this request from JavaScript. You'll need to make a server side request. There are many implementations of this flow in PHP, C#, Java, etc.
I'm posting my ajax code here that has worked for me and this CORS error in console doesn't matter. If you see in network you will get the access token.
see the ajax code below.
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
I hope this will work for you perfectly.
I think you need to add the origin URL/IP in CORS setting as well in salesforce if you are making a request from Javascript app so it can get access to salesforce data.

jQuery and Ajax - cannot POST

I am trying to login to a website using a known username and password and to get some data displayed from the site for a specific user account on that website. I am using jQuery and Ajax for this purpose. This is my code:
$.ajax({
async: false,
cache: false,
type: 'POST',
dataType: 'json', // json...just for example sake
data: ({
'login_username': username,
'secretkey': password
}),
url: 'https://mail.someserver.com/src/redirect.php',
success: function (data) {
alert("SUCCESS!")
if (data === '1') { // server returns a "1" for success
// success!
// do whatever you need to do
} else {
// fail!
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// something went wrong with the request
alert("Failed!");
}
});
I've already made my search around the web and I know that browsers do not permit cross server ajax calls to prevent security issues, but I've already tried to use "jsonp" as dataType to no avail :(
So, what am I doing wrong?
Be sure that your url is not breaking the same origin policy -- that is, the request coming from the client cannot request data from a server from a different domain (there are exceptions to this rule, namingly CORS, but that requires that you make changes to the server/application you're talking to).
The solution to your problem would be to make the request from some server-side script, then in turn having your client application query that script, based on the same machine that's serving the application to the web.
My fault isn't at the code above, my fault was that in my manifest file (I am building a Google Chrome extension) I didn't have set proper permissions (https://*).
Sorry for the frustration!

jQuery AJAX Cross Domain with BASIC Authentication

I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.
What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.
<script type="text/javascript">
$(document).ready(function() {
var tok = 'username' + ':' + 'password123';
hash = btoa(tok);
authInfo = "Basic " + hash;
$.ajax({
url: "http://username.beanstalkapp.com/api/changesets.json",
beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
type: "GET",
async: false,
crossDomain: true,
dataType: "json",
success: function(html){
console.log(html);
},
error: function(html){
console.log('error');
}
});
});
</script>
If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!
You will need to make proxy for cross-domain ajax requests.
Usual scenario looks like this:
Client send ajax request to server
Your server forwards request to external/remote server
Waiting on response from remote server
Parse and process response from remote server
Send response back to client
If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.
you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.
Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.

Categories