carol1287
carol1287

Reputation: 395

ServiceStack + Ajax Authentication Call

I am trying to get my ajax call to work to connect to an API that uses ServiceStack. The problem I am having is the authentication. In C# I do the call like this:

  string json = "";
  JsonServiceClient client;
  client = new JsonServiceClient("https://api.domain.com");
                            client.SetCredentials("test", "test");
                            client.AlwaysSendBasicAuthHeader = true;

  try
  {
     List<AppleResponse> response = client.Get<List<AppleResponse>>("/v1/getdata?id=1");
     json = response.ToJson();
  }
  catch (Exception ex)
  {
     json = ex.Message;
  }

  JArray v = JArray.Parse(json);
  var total = v[0]["total"].ToString();

I get the value of total, for example total=10 Now I want to do the same thing using an Ajax call. Here is a sample call without authentication:

        function Getdata(id) {
            $.ajax({
                url: '//api.domain.com/v1/getdata',
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ id_s: id }),
                success: function (f) {
                    $.each(f.d, function (i, e) {
                        alert(e.total);
                    });
               },
                cache: false
            });
        }

Does anyone knows how could I add the authentication BUT without showing the username/password in the javascript markup? Thanks a lot.

Upvotes: 0

Views: 531

Answers (1)

reptildarat
reptildarat

Reputation: 1036

Well, since you use basic authentication, there's no way to not reveal your username or password. but you can make it work like this:

function Getdata(id) {
    $.ajax({
        url: '//api.domain.com/v1/getdata',
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ id_s: id }),
        beforeSend: function(xhr) { 
            xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password)); 
        };
        success: function (f) {
            $.each(f.d, function (i, e) {
                alert(e.total);
            });
       },
        cache: false
    });
}

But, if you do not want to reveal your username or password, you need to build your own authentication filter that accept your custom header.

you can see how in this: Servicestack wiki

And then you can save your auth token and send it like this:

function Getdata(id) {
    $.ajax({
        url: '//api.domain.com/v1/getdata',
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ id_s: id }),
        headers: { 'my-auth-header': 'myToken' },
        success: function (f) {
            $.each(f.d, function (i, e) {
                alert(e.total);
            });
       },
        cache: false
    });
}

Upvotes: 4

Related Questions