BeNdErR
BeNdErR

Reputation: 17927

Retrieve OData using AJAX in json format, with authentication

I need to convert this OData retrieval (using SAPUI5 libs):

var url = "http://someurl/SERVICE";
var username = "username";
var password = "password";
var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);

into an ajax call, without using SAPUI5 libraries, mantaining the authentication:

$.ajax({
   url : "http://someurl/SERVICE?$format=json",
   type: "GET", //or POST?
   dataType: "json",
   data : {username : "username", password: "password"},
   success: function(){alert("ok")},
   error: function(){alert("error")}
})

I googled a lot but I didn't find anything useful.. I don't know how can I do the authentication.

is it possible? Any idea?

Upvotes: 1

Views: 10301

Answers (1)

decho
decho

Reputation: 331

Instead of setting "data:..." you need to handle this in such way :

$.ajax({
   url : "http://someurl/SERVICE?$format=json",
   type: "GET", //or POST?
   dataType: "jsonp",
   xhrFields: 
        {
            withCredentials: true
        },
   beforeSend: function (request)
        {
            request.setRequestHeader("Authorization", "Basic  dG9tY2F0OnRvbWNhdA==");
        },
   success: function(){alert("ok")},
   error: function(){alert("error")}
})

Where "dG9tY2F0OnRvbWNhdA==" is base64 encoded user and password. And of course, this will work only for Basic authentication.

Or another option is to put user/password in the url directly :

$.ajax({
   url : "http://user:password@someurl/SERVICE?$format=json",
   type: "GET", //or POST?
   dataType: "jsonp",
   success: function(){alert("ok")},
   error: function(){alert("error")}
})

Upvotes: 2

Related Questions