Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling my web api from jquery securely

I have a simple question that may point out to a complicated answer :(

I have a web api which works fine. But now I want to set up Authentication/Authorization. I need it to work on all platforms, but mainly from jQuery. Naturally I don't want to send my username and password along the pipeline in plain text like this:

function GetAllCategories() {
    var credentials = $.base64.encode('r3plica:mypassword');
    var authType = "Basic " + credentials;

    $.ajax({
        url: "http://localhost:18904/api/Categories",
        type: "GET",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", authType);
        },
        success: function (data) {
            alert('Success!');
        },
        error: function () {
            alert('error');
        }
    });
}

so I have been looking at other alternatives. Is the only alternative to use 3 legged OAuth? I was hoping to just pass a query string key/value to my api and let that handle everything but I just can't find a step by step process for doing that. Everything seems so complicated.

So, does anyone know of anything I can do? I have read loads and tried to implement loads of stuff.

I managed to get this working: http://codebetter.com/johnvpetersen/2012/04/04/moving-from-action-filters-to-message-handlers/ From what I can tell though, you need to encrypt your string (username) prior to sending to the api using your public key and then the api will decrypt using a private key and authorize you.

so my 2 questions are simple :)

  1. Can you use the above link and call from jQuery easily (i.e. not using 3rd party libraries)
  2. If not, what is the best way to go about securing my API so that it can be called directly from an jQuery.ajax call?

Just to clarify, I am using SSL for the API

Cheers in advance,

/r3plica

like image 354
r3plica Avatar asked Feb 26 '26 23:02

r3plica


1 Answers

For Websites (where the user can look into the sourcecode) we generate through PHP an AuthenticationToken and put it into javascript. The token changes every page reload.

for example:

<script type="text/javascript">var authToken = '<?=genToken();?>'</script>
[...]
$.ajax( [..]
    beforeSend: function (xhr) {
        xhr.setRequestHeader("ownToken", authToken);
    },

and check that Token Serverside.

like image 135
take Avatar answered Mar 02 '26 05:03

take



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!