开发者

JQuery $.ajax.post to a service with secret API Key

let's assume that there is a开发者_JS百科 service out there as following;

http://exmaple.com/service1/GetSomething?apikey={api-key-goes-here}

an my api key is : 96a143c8-2f62-470c-b81f-dec5fc271873

so we will be making calls to > http://exmaple.com/service1/GetSomething?apikey=96a143c8-2f62-470c-b81f-dec5fc271873 link and it gives back the response as JSON.

when I consume that with JQuery (or any other client side JavaScript library), how will that key will be secure? I am thinking that and I figured there is no way. If I am going to make a call to that service with client side call, it will be our in the open.

any idea on this?

thanks.


Make a proxy.

Post the values to one of your pages and from this page make the real request on the server-side, then return the value you get.

Of note: You cannot make a cross-domain request with javascript, mainly browsers don't allow this for security reasons.


the only way to secure it from a client perspective is to proxy request to API on your server and adding that key in your app.


The best approach that I found was to give your user an API_KEY and a SECRET_KEY.

Build your REST API request passing in the API_KEY, timestamp and any other parameters necessary for making the call.

Using a scripting language like PHP create an API_SIGNATURE variable using two way encryption with your SECRET_KEY and append that to your base url and that is what you fire off as your request.

Now anyone can see that request and that is why you put the timestamp in as a parameter. Basically you can put in a constraint that will only process requests that are less than one minute old.

Example: (do this part in scripting language)

$API_BASE_URL="http://api.yourdomain.com/1.1/comments.json?api_key=2002&timestamp=2323234544&id=4";
$API_KEY=300;
$API_SIGNATURE=hash_hmac('sha256', API_BASE_URL, API_KEY);
$API_URL=$API_BASE_URL.'&api_signature='.$API_SIGNATURE;

--

Now in your jquery ajax url: echo out $API_URL using PHP.

--

In your API when you get a request you lookup the users account based on API_KEY and get their SECRET_KEY and decrypt the signature and make sure that matches what was passed in. If that passes now check the timestamp and make sure the request is less than a minute old.

You can also do rate limiting and a whole bunch of other stuff before processing the request.

Thats it.


Also people are saying cross domain requests are not allowed by browsers. That is true if you are requesting json but you can get around this using jsonp.


The hash_hmac is available in many programming and scripting languages. So if you develop an API you can use it on the web with PHP and in your iphone app with objective c.

Pretty simple.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜