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.
Related
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.
I am facing problem while requesting url
In documents for web service access there are required parameters as UserID, queryparam , and header as
x-requested-by
2nd thing I have noticed
I am having my browser url to run code is as
01234.domain_name.com/my form.html
And my request url is as
09876.domain_name.com/serviceapi/
Where domain_name part is same.
While posting data I am using code as:
URL: 09876.domain_name.com/serviceapi/+ name + '?u=UserID';
$.ajax(function(){
type: post,
url: URL,
data: datajsonobject,
headers: {x-requested-by: UserID},
success: successfun
});
Code is typing on mobile , please ignore caps lock mistakes in code.
After running this code getting 401 response. Plz help me
Status code 401 stands for Unauthorized. You need to login into your application and then make an Ajax call or your credentials are wrong.
Maybe you can have a debug point in the code where user authentication is being handled.
I am trying to use the lastFM API. I have started with a very basic template where all i wanted to do was connect to the LastFM API and authenticate myself. I have a button on my HTML page -
<button id="auth">AUTHENTICATE</button>
Here's the jQuery function to handle the click event -
$(document).ready(function() {
$("#auth").click(function() {
console.log("authenticate called");
var myUrl = "http://www.last.fm/api/auth/?api_key=32*************8a*****2";
/*$.get(url,function(data) {
alert("data");
});*/
$.ajax({
// The 'type' property sets the HTTP method.
// A value of 'PUT' or 'DELETE' will trigger a preflight request.
type: 'GET',
// The URL to make the request to.
url: myUrl,
xhrFields: {
withCredentials: false
},
crossdomain : true,
headers: {
// Set any custom headers here.
},
success: function(data) {
// Here's where you handle a successful response.
},
error: function(data) {
console.log(data);
});
});
});
I am running this on my localhost. As you can see from the AJAX request, it supports CORS. I can also see CORS header attributes being added to my request headers. But the server needs to respond with the CORS headers too like Access-Control-Allow-Origin. But the response does not contain any such headers.
But lastFM API supports CORS, so shouldn't it be sending these attributes in the response headers? Also, now how can I make use of CORS to authenticate my application?
P.S - I know I can use JSONP, but I want to know if there is any way I can handle this using CORS?
Thanks to #potatopeelings, I got the answer. What we need was not to call the authentication url, but to redirect it to a seperate page which will ask me to authorize the application to use the lastFM account. I also provided a callback URL which will redirect to my application after I have given the authorization.
So my final URL is like -
myURL = "http://www.last.fm/api/auth/?api_key=XXX&cb=http://localhost:63342"
And I removed my AJAX call to do the following -
window.location.replace(myUrl);
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.
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.