Question

I am attempting to build a Delphi XE2 DataSnap Rest server to be used as a 3rd party API for access to our DBMS.

I have extended the functionality of the sample methods provided when using the rest datasnap wizard in xe2 with authentication and authorization.

I can confirm that all the server methods I have written do pass back the data expected when accessed directly through the browser.

The issue comes from trying to authenticate to the server from a $.ajax() call.

When accessed from the browser address bar, you are prompted for the username and password and, when you enter "dev" for both, allows you to continue.

When setting the ajax() username and password params to "dev", I am getting a HTTP 401 response.

I think I am doing it correctly, but here is the code snippet:

$("#contentdiv").click(function(){
        $.ajax({
            type:"GET",
            cache:"false",
            username:"dev",
            password:"dev",
            url:"http://192.168.0.2:8080/datasnap/rest/TServerMethods1/methodname/",
            dataType:"jsonp",
            statusCode: {
                200: function(data){
                    alert('success ');
                }
            }               
        });
});

If I turn off authentication, I can successfully get a HTTP 200 response (albeit with a syntax error in the JSON Delphi DataSnap is returning, but that is a question for a different time).

Also, what is worth know - if I log in manually and then run the ajax, it works - I am assuming that this is because the credentials are cached or some such.

Quite new to both these technologies, so be gentle. If I've left something out that could be of import, let me know and I will get it up here.

Was it helpful?

Solution

Your Ajax code uses JSONP, the server uses basic authentification.

A comment on this answer says that JSONP cannot contain the USER / PWD headers which Basic Auth requires:

Basic Authentication with jQuery.ajax request and jsonp

The reason is (quote from the answer above):

JSONP works differently, it's a GET request via a tag include to get the file, so you're not sending special headers or anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top