Consuming the MS Web CRM API in 3 party Application - dynamic

I have created an website wherein I'm trying to call the MS Web CRM as below
$(function () {
var ODataURL = "https://***.crm5.dynamics.com/xrmservices/2011/OrganizationData.svc/Core_territorytypeSet";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
//
// e.g. data.d.results
alert(JSON.stringify(data));
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
});
I'm getting 'unauthorized' error.
How can we authorize the user before making call to the Api in javascript??
Thanks in advance

You would first need to register your application with Azure Active Directory. Then use the client id to retrieve a token that need to be passed with your web API calls. You can find a good walkthrough here: https://msdn.microsoft.com/en-us/library/mt595797.aspx

Related

Consuming authorized asp.net webapi service using jQuery ajax

I'm developing IPAD Application using phone gap, HTML5, and jQuery. My webservice is built upon ASP.NET WEBAPI with forms authentication. while accessing api, authentication window is asking for username and password. After providing username and password we can get the result. But while consuming the same service using jquery ajax, error thrown with a message "Unauthorized". Can any one help on this issue.
ScriptBlock in which i m accessing the url
$.ajax({
type: 'POST',
url: 'https://myservice.com/api/mypostmethod',
data: {
'item': ItemXml,
'room': RoomXml
'User_Id': 12313
},
success: function (result) {
ProcessResponse(result);
},
error: function (xhr, textStatus, error) {
console.log("Local To Live - " + xhr.statusText);
console.log("Local To Live - " + textStatus);
console.log("Local To Live - " + error);
}
});
How to call this service? I also tried to user jQuery xhr headers and used code is as below
function getAuthorizationHeader(username, password) {
var authType;
if (password == "") {
authType = "Cookie " + $.base64.encode(username);
}
else {
var up = $.base64.encode(username + ":" + password);
authType = "Basic " + up;
};
return authType;
};
$.ajax({
type: 'POST',
url: 'https://myservice/api/mypostmethod',
data: {
'item': '',
'room': '',
'User_Id': 12313
},
beforeSend: function (jqXHR, Settings) {
var AuthHeaders = getAuthorizationHeader("username", "password");
jqXHR.setRequestHeader("Authorization", AuthHeaders);
},
success: function (result) {
ProcessSyncResponse(result);
},
error: function (xhr, textStatus, error) {
alert("Error - StatusCode : "+xhr.status );
}
});
Kindly help on this issue.
Thanks.
If you're set on using forms authentication, take a look at this article for an example on how to use it over AJAX calls. Make sure you're communicating with the service over HTTPS or else you'll have major security problems.
I think the better solution would be to implement some kind of token authentication so you're not passing the username/password in your requests and don't have to maintain some kind of stateful connection with the server. You should look into this.

400 Bad Request - https://accounts.google.com/o/oauth2/token

can anyone please tell me why this is bad request
var searchurl = "https://accounts.google.com/o/oauth2/token";
$.ajax({
dataType: "json",
url:searchurl,
context: {code:auth_code, client_id:'clientid', client_secret:'secret', redirect_uri:'http%3A%2F%2Flocalhost:8085%2FGmailIntegration%2FgetAuthResponse.jsp', grant_type:'authorization_code'},
type:"POST",
contentType:"application/x-www-form-urlencoded",
success:function(data) {
alert(data);
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
I got this working.. i am sharing the code for those who are stuck with this:
$.ajax({
dataType: "json",
url:searchurl,
data: {code:code, client_id:'clientid', client_secret:'secret', redirect_uri:'http://localhost:8085/GmailIntegration/getAuthResponse.jsp', grant_type:'authorization_code'},
type:"POST",
contentType:"application/x-www-form-urlencoded; charset=utf-8",
crossDomain:true,
cache : true,
success:function(data) {
alert(data);
},
error: function(jqXHR, exception, errorstr) {
console.log(jqXHR);
alert(errorstr);
}
});
but now i have new issue. The url get 200 OK response but i am not getting response at all
OAuth2 user agent flow is recommended for JS clients, see https://developers.google.com/accounts/docs/OAuth2UserAgent
Is there any specific reason you want to use the web server flow in a JS app?

How do I perform a video search with Vimeo API version 3 (beta) and jQuery Ajax?

Late Breaking Update:
Hi Dashron,
I've been doing some independent research & what I am seeing is that every other video API that supports jQuery Ajax i.e. JSONP will deliver the following file during an API call:
crossdomain.xml which basically looks like this:
<cross-domain-policy>
<allow-access-from domain="*" />
<allow-http-request-headers-from domain="*" headers="*" />
<site-control permitted-cross-domain-policies="master-only" />
</cross-domain-policy>
This is at the heart of CORS.
I get this file from YouTube, SoundCloud and DailyMotion.
However when using fiddler utility to debug the Vimeo API testing as per your suggestions this file never shows up in the traffic interchange.
Further if I change the Ajax call type to merely JSON (no JSONP) I get a 302 response which indicates a redirect but does show the accept header as per your instructions. Obviously JSONP is required or clientside API is useless but this leads me to believe your API team has:
A. Not tested jQuery AJAX and;
B. Has not enabled CORS
I hope this helps you get API v. 3.0 CORS compliant for jQuery Ajax JSONP traffic.
Thanks,
Len
Original Missive:
I am trying to use jQuery Ajax to perform a simple videos search.
According to Vimeo API support this is supported with the new beta api version 3:
Excerpt from their email to me:
The good news, is API3 will support this feature. It is currently in Beta, but we have many people using it in production apps.
You can create a new app at https://developer.vimeo.com/apps/new?oauth2=enabled, or enable it on your app by adding “?oauth2=enabled” to the end of your apps edit page.
You can find VERY EARLY documentation at developer.vimeo.com/api/docs.
As long as you don’t include your application secret in your requests, everything should work fine.
Let me know if you run into any issues!
END EXCERPT
I have tried to do this unsuccessfully with the following code:
var urlX = 'http://api.vimeo.com/videos?query=elvis';
$.ajax({
url: urlX,
type: "GET",
beforeSend: function (req) {
req.setRequestHeader("Vimeo-Client-ID", "<My API Key>");
req.setRequestHeader('Content-type', 'application/xml; charset=UTF-8');
},
dataType: "jsonp",
success: function (data) {
alert("SUCCESS");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
}
I built this by referring to the following spec:
https://developer.vimeo.com/api/docs/spec
This does not work. Can anybody help as it has been 3 days without any further responses from Vimeo API support.
Thanks!
UPDATE:
I tried this and it does not work. Please supply sample code to save time all around. Thanks very much!!
Thanks for the reply. Unfortunately this does NOT work:
urlX = 'http://api.vimeo.com/videos?query=elvis&client_id=XXXXXXXX';
$.ajax({
url: urlX,
type: "GET",
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/vnd.vimeo.*+json;version=3.0');
},
dataType: "jsonp",
success: function (data) {
alert("SUCCESS");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
I also tried this UNSUCCESSFULLY... :((
urlX = 'http://api.vimeo.com/videos?query=elvis&client_id=XXXXXXXX';
$.ajax({
url: urlX,
type: "GET",
headers {
"Accept": "application/vnd.vimeo.*+json;version=3.0"
},
dataType: "jsonp",
success: function (data) {
alert("SUCCESS");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
I tried this unsuccessfully too:
$.ajax({
url: urlX,
type: "GET",
headers {
"Content-Type": "application/vnd.vimeo.*+json;version=3.0"
},
dataType: "jsonp",
success: function (data) {
alert("SUCCESS");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
And finally I tried this as per the following StackOverflow article:
Cannot properly set the Accept HTTP header with jQuery
$.ajax({
url: urlX,
type: "GET",
headers {
Accept: "application/vnd.vimeo.*+json;version=3.0",
"Content-Type": "application/vnd.vimeo.*+json;version=3.0"
},
dataType: "jsonp",
success: function (data) {
alert("SUCCESS");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
Without any specific error message I have no way of deducing a solution and would be tremendously grateful if a working example were supplied. I am sure it would help other jQuery developers using v3.0 API.
Thanks!!
UPDATE - Looks like a cross-domain security issue
One of my developers took a look at this and suggested that since json went through but not jsonp there is a "CORS" iissue; in other words your API does not allow cross-domain requests as per the error received:
Error: jQuery18305652002056594938_1376096997218 was not called
I think you guys should absolutely test this from a domain other than vimeo.com as we can go back & forth forever but if cross-domain calls are not being supported no amount of coding on my part can affect that. That is a job for your staff to enable cross-domain requests.
urlX = 'http://api.vimeo.com/videos?query=elvis&client_id=d0b4a83fc5c12570e9270fc54ef6ecabb8675fcf';
$.ajax({
url: urlX,
type: "GET",
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/vnd.vimeo.*+json;version=3.0');
},
dataType: "jsonp",
success: function (data) {
alert("SUCCESS");
},
error: function (xhr, ajaxOptions, thrownError) {
$("#errorMsg").text(thrownError);
}
});
}
Thanks,
Len
Thanks to Vimeo support I was finally able to achieve a working sample. My error was assuming that JSONP was required even though it is not. Since Vimeo is CORS enabled in version 3.0 of their API the jQuery getJSON() function will work cross-domain.
Here is a working sample. Hopefully this will save someone a bit of time and effort.
function TestVimeo() {
urlX = 'https://api.vimeo.com/videos?query=elvis&client_id=XXXXXXXXXXXXXX';
$.getJSON(urlX, function (data) { console.log(data); })
.success(function (payload) {
console.log("second success");
})
.error(function (jqXHR, textStatus, errorThrown) {
console.log('******* ' + "error: " + textStatus + ' *******');
});
}
It looks like the specs are out of date.
The Vimeo-Client-ID header is no longer respected.
All you need to do is add your client id to the url as a querystring parameter.
http://api.vimeo.com/videos?query=elvis&client_id=XXXXXXXXX
Additionally, you will need to provide the proper accept headers as stated in the docs, Accept: application/vnd.vimeo.*+json;version=3.0

Same Origin Policy Error when using jQuery JSONP with CloudFlare API

I recieve an error (XMLHttpRequest cannot load https:// www.cloudflare.com/api_json.html?tkn=&email=&z=&a=rec_load_all&callback=%3F. Origin http:// domainmanager.tech-bytes.org is not allowed by Access-Control-Allow-Origin.) (spaces inserted in URLs due to Stack Overflow link limit) when trying to send a JSONP request via jQuery to CloudFlare. The CloudFlare API states that you can ask for a JSONP callback by appending a &callback=mycallback parameter. I am not sure if I am supposed to replace mycallback with something, I tried replacing it with ? as that is what some other resources said, or if I have to do some other modifications to my code.
Try in this way for cross domain request.
$.ajax({ url: "yourUrl",
data:{paramName1: JSON.stringify(paramValue1),paramName2: JSON.stringify(paramValue2)},
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data) {
alert(data.d);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
You can use CORS for this purpose.
Example code:
jQuery.support.cors = true;
function CrosDom_ajax(url) {
if (window.XDomainRequest
&& $.browser.msie
&& $.browser.version < 10) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert(xdr.responseText);
};
xdr.open("get", url);
xdr.send();
}
}
else {
$.ajax({
url: url,
success: function (response) {
},
error: function (data) {
}
});
}
}
Also you need to Write the following code in server side, to allow cross domain access
Response.AppendHeader("Access-Control-Allow-Origin", "*");

jQuery Ajax call returning null from WCF RIA REST service

I have created a WCF REST .NET 4 service and deployed it to a local IIS 7.
If I use Fiddler and use the request builder, I am able to call the service and see the data been returned OK. If I try hitting the same REST location in the browser, JSON is not been returned but it looks like XML.
My service looks like this:
[OperationContract]
[WebGet(UriTemplate = "/{id}/details.json",
ResponseFormat=WebMessageFormat.Json)]
public SampleItem Get(string id)
{
return new SampleItem{ Id=1, StringValue="value from string"};
}
My web.config file has only a slight change:
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"/>
I am trying to call the service using jQuery like this:
$(document).ready(function () {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://wcf-rest/service1/1/details.json",
dataType: "json",
success: function (data) { alert(data); },
error: function (e) { alert("error"); }
});
}); // end .ready
However, null is being returned every time. What do I need to change?
I've been using jQuery and Ajax extensively with a JSON datatype, and I believe you need to change data to data.d. See my example below.
function getMakes() {
$.ajax({
type: "POST",
url: "../../WebService_VehicleAssignment.asmx/getAllVehicleMakes",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var response = msg.d;
$('#output').empty();
$.each(response, function (vehicle, vehicle) {
$('#output').append(new Option(vehicle.Make, vehicle.Id));
});
},
failure: function (msg) {
alert('failure');
}
});
}<br />
I use Firebug to debug this stuff. I can see exactly what's getting posted to the web service and what is coming back. And if the web service is complaining, what it's complaining about.
Read about why the .d is necessary in A breaking change between versions of ASP.NET AJAX. In short, I believe it is a wrapper so that returned data is treated as a string rather than being returned and executed if it is raw literal JavaScript code.