Reputation: 2655
I have a question regarding the allowing the user to connecto only allowed domain name.
So what i have in mind is: i have a list of domaina names, like *.domain1.com; *.domain2.com etc ...
Then somwhere in the code I have to check if the request or response is really from that kind of domain, if it is not, i should throw a message.
Here i have the code which i have at this moment:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
if (stream == null)
{
return null;
}
return stream;
}
}
Any idea?
Upvotes: 0
Views: 1183
Reputation: 6566
Use the ResponseUri
property:
HashSet<String> allowedDomains = new HashSet<String>()
{
"domain1.com",
"domain2.com"
};
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
using (WebResponse response = request.GetResponse())
{
if (!allowedDomains.Contains(response.ResponseUri.Host))
{
throw new IllegalDomainException();
}
using (Stream stream = response.GetResponseStream())
{
if (stream == null)
{
return null;
}
return stream;
}
}
You might want modify the comparisson: for example, iterate backwards over the result of request.ResponseUri.Host.Split(".")
comparing each part in turn with the equivalent from the allowedDomains value, and you might want to think about where the check is done: do you want redirection to be permitted? If so, create a Uri object from the user input, and check the Host
property of that.
Upvotes: 1
Reputation: 64923
Usually this is acquired using the UrlReferer HTTP header, but this header isn't mandatory: it can be set or not. It depends on the HTTP server.
The whole header may be accessed using the HttpWebResponse.Headers
property:
((HttpWebResponse)response).Headers["Referer"]
Honestly, I would like to suggest you that the best solution is to use an application key (an arbitrary identifier). For example a Guid
(it may work for very simple cases).
In the Web server you can define default headers (if your Web sites are developed using ASP.NET, you can do it in the web.config) so any request coming from the whole server will contain your arbitrary HTTP header with the appkey.
That is, you can define an arbitrary header that may identify the HTTP responses coming from your Web sites. For example: MySite_AppKey. Using this approach you should verify that any HTTP response contains the whole MySite_AppKey and check if the whole appkey is permitted in some white list.
Sample pseudo-code:
if(AppAuthorizationManager.IsAuthorized(response.Headers["MySite_AppKey]))
{
// Do stuff for the authorized request
}
Note that I'm describing a very simple implementation.
Upvotes: 0