Blog

Filter posts by Category Or Tag of the Blog section!

Open redirection attack in asp.net MVC

Monday, 07 July 2014

In the simplest definition, Any web application that redirects to a URL by a request (querystring) can tamper to an external, malicious URL by hackers. This operation is called an open redirection attack. In asp.net MVC, in server side, you can use the following HTML helper to check if the requested URL is local or not:

 

 

  public static bool IsLocalUrl(this HtmlHelper htmlHelper, string url)

        {

            var request = HttpContext.Current.Request;

 

            if (string.IsNullOrEmpty(url))

            {

                return false;

            }

 

            Uri absoluteUri;

            if (Uri.TryCreate(url, UriKind.Absolute, out absoluteUri))

            {

                return String.Equals(request.Url.Host, absoluteUri.Host,

                            StringComparison.OrdinalIgnoreCase);

            }

            else

            {

                bool isLocal = !url.StartsWith("http:", StringComparison.OrdinalIgnoreCase)

                    && !url.StartsWith("https:", StringComparison.OrdinalIgnoreCase)

                    && Uri.IsWellFormedUriString(url, UriKind.Relative);

                return isLocal;

            }

        }

 

You can create your own function in JavaScript too, but I think server side one is safer!

comments powered by Disqus