Click here to Skip to main content
14,695,085 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have protected RestFul web service which has several interfaces that user can access. User can access these interfaces after proper authorization and authentication i.e. over https. I have downloaded a RestFul Client for FireFox from which I am setting some custom headers and in body I am providing the login credentials. I am able to login to the Web Service and able to access the other interfaces.

But I am writing a code using jQuery, Ajax thru which I tried to call this service but I am receiving "HTTP/1.1 400 Bad Request" as a response. Following is the code


<script type="text/javascript">
    var xhr,jqXHR;
    if(!xhr && typeof XMLHttpRequest != "undefined") 
    {
        xhr = new XMLHttpRequest();
    } 

self.ajax = function(uri, method, data) {
    var request = {
        url: "https://mysite/login",
        type: "Post",
        // Content-Type: "application/json", 
        //headers: { 'My-Key': 'ACNDSDSKER$%$%$#$#$#$#$"' },
        accepts: "application/json",
        data: {  // the parameters of the request. This should be adapted to your case
            "uid": username,
            "password": password
        },
        cache: false,
        dataType: 'json',
        data: JSON.stringify(data),
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
            xhr.setRequestHeader("My-Key", btoa("ACNDSDSKER$%$%$#$#$#$#$"));
        },
        success:function (jqXHR) {
            alert("ajax success " + jqXHR.status);
        },
        error: function(jqXHR) {
            console.log("ajax error " + jqXHR.status);
        }
    };
    return $.ajax(request);
</script>


First I tried to provide custom headers using "headers" attribute but it gives the same error. Second I tried this with beforeSend function but the result is same. Third I tried to encode the login credentials using basic HTTP protocol but no use. It gives the same error.

Note:- In Rest Client I do not need to provide "Authorization" as a custom headers. Also the protocol it uses is "HTTP authentication--OAuth Protocol".

Please let me know what could be reason the same request made by Rest Client works fine but not with the code written in jQuery, Ajax.


I also would like to know whether we need to send certificate details with the request to authorise the user. If yes, then how to send it thru jQuery,Ajax or do we need to other lang like (java,php.....).

pls suggest.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900