calling my web api from jquery securely

2019-05-18 07:21发布

问题:

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

回答1:

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.



回答2:

You don't have many options to secure your application in an optimal way since all calls are made from the front end application so calls can always be sniffed.

However you can consider to use ssl in combination with asp.net authentication.

Please look at my other post for authentication possibilities: ASP.NET Web API Authentication Options

Coming back to your questions: What you are trying to achieve can simply be done using asp.net forms authentication. You can decorate your view methods (in your controller class) using the Authorize attribute;

    [Authorize]