1

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.

1 Answers1

0

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.

jebar8
  • 2,113
  • 3
  • 21
  • 31