开发者

Lock down API to specific URL

开发者 https://www.devze.com 2023-03-11 11:13 出处:网络
This might be a stupid question and/or simple answer, or neither. I am developing an API, and I was wondering if it was possible to lock this down to a specific URL/Host?

This might be a stupid question and/or simple answer, or neither.

I am developing an API, and I was wondering if it was possible to lock this down to a specific URL/Host?

e.g. My API is on one url, and it only responds to a httpwebrequest from a specific url. www.apione.com only responds to www.apitwo.com

Is this possible开发者_StackOverflow? I have been looking into the host headers but don't think it is possible to get this information.

Thanks


If your "API" as a web service then you can use 'Request.UrlReferrer' to get a URI object that tells you the URL the request has come from. You can then simply check that it matches one or more expected values before doing anything. This will not stop request from other URLs hitting the service but your web service would not do anything in response to these requests. You can also lock down by IP in a similar manner by using Request.UserHostAddress. Please note that these do different things. If the user clicks a link on www.apione.com the referer will be set to www.apione.com but the IP will be the IP of the user. Which method you use would depend on how the API is consumed. e.g. If there is some server side process that runs from www.apione.com then the referer would not be much help. Also referer can be easily spoofed.


I realize this is a very old post, but I thought it might be helpful to add a simple, secure practice to address this issue in future implementations.

Embed a random API access token on your page, linked to the session. You can optionally refresh the token at each request if you wish to prevent inadvertent double-submits and so forth.

On the page

token = get random string, 8 to N characters long,
    hashing if you desire greater security
store token in session

write some html
embed the code in a script tag:
    var api_token = '<? echo code; ?>';

append api_token to all SOAP/JSONP requests
when the request returns, replace api_token with the new token

In the service

read api_token
look for api_token in session
if token does not exist, exit
else, continue ...
generate new token
store token in session
append token to response

This basic strategy is good for protecting service requests and validating link-clicks. I.e., you can verify with high certainty that delete.aspx?id=123 originated from manage.aspx or whatever, rather than from someone's FB feed, twitter, short URL service, etc..

0

精彩评论

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