Introduction
This code snippet is useful to get the original URL from a shortened one. This will help its user to check the origin of the URL and will give idea about if you really want to visit that site or not.
Background
URL shorten services are quite popular today. But as a security point of view I always like to know about the origin of the link rather then blindly trusted on the shorted link. This particular codes will help one to check its link without redirecting to the attackers site and yet gives you the original link.
Using the code
This code demonstrates the uses of the simple technique mentioned here. You need a simple website with a Text box, a Label and a button on the Form. When user click on a button it will first check if anything in the TextBox1 and has valid Url by using isValidUrl static method.
If url is valid then it will uses ServerVariables and creates a request and call GetRespose in response object. All we need to at this point is to set a label1.text property with uriString.
string url = TextBox1.Text;
if((TextBox1.Text != "") && (isValidUrl(ref url)))
{
string userAgent = Request.ServerVariables["HTTP_USER_AGENT"];
HttpWebRequest request = (HttpWebRequest)(WebRequest.Create(url));
request.UserAgent = userAgent;
request.AllowAutoRedirect = false;
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
string uriString = response.Headers["Location"];
Label1.Text = uriString;
}
}
else
{
Label1.Text = "You have entered Invalid URL. Please enter valid URL in Text box.";
TextBox1.Focus();
}
Points of Interest
I have then tested some URLs and the result was as expected, working fine. I guess there is no need to say that I haven’t tested my application with all URL shortening services, so you may find bugs with some other shortening services. If so, please let me know by using the comments section below.
I know some of you might suggest that I should use url validation at the client side by using jQuery or JavaScript. I am interested as well but the point was here to demonstrate "how to reverse a shorten URL" and to that respect I have keep this as simple as possible.
History
Initial Draft saved.