Get the Domain that an Ajax Request is coming from
I have a set of JSONP Web Service created on my J2EE application, which will be used by a website under a different domain. The web services have been created using the Jersey framework.
What I want to know is, is there a way I can tell in my Web Service code, what domain the request came from? What I'm hoping is that there is a value in the HttpHeader which would have this value.
Also would it be possible for the user making the Ajax call, to fake this value, or to put in another value before they send the call?
What I'm hoping to use this for is to restrict the domains that can call my web service. I need to use JSONP, but i don't want my web service to be available to anybody who reverse engineers my JavaScript code.
Or does 开发者_如何学运维anybody know another way of doing this?
You can use HTTP_REFERER as already mentioned
Some code example: talker.php
<html>
<head>
<title>HTTP Referer example</title>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div class="result"></div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'observer.php',
success: function(data) {
$('.result').html(data);
}
});
});
</script>
</body>
</html>
observer.php
<?php
echo $_SERVER['HTTP_REFERER'];
?>
The result looks like this:
http://localhost/talker.php
One way to achieve this would be to authenticate the users on the distant domain which is supposed to send the request. So for example the server on the distant domain could emit some encrypted value to authenticated users. Then when sending the JSONP request you would send this token to the web service which would decrypt it. The idea is that both servers should share some common secret to encrypt/decrypt this token. This way you can ensure that the request came from the other server.
Your RESTful services are hosted on a web server and with REST you're limited to the standard stuff that comes as part of HTTP. For example, you could get the host IP that sent the request, but be aware that this can be spoofed.
One option open to you would be to require the web service requests to be digitally signed. This basically means that the caller creates and adds a Message Authentication Code to the request. The MAC is generated using a secret key that only an authorised user of your service knows. You can (and should) also add a user ID to the web service request, allowing you to give each user their own secret key.
Remember that if your services are being called by javascript (eg using AJAX) then the calls will come from the client computer. This means they are completely open to reverse engineering. If you rely on javascript to digitally sign the request then the javascript would need to know the secret key, therefore exposing it to any attacker.
精彩评论