Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pedrovasconcellos/2192824a0739c0a5934397f56df2bce2 to your computer and use it in GitHub Desktop.
Save pedrovasconcellos/2192824a0739c0a5934397f56df2bce2 to your computer and use it in GitHub Desktop.
Preventing redirection attacks for other domains (C #)
//Note: Before using these two functions read this
//https://docs.microsoft.com/pt-br/aspnet/mvc/overview/security/preventing-open-redirection-attacks
public static class PreventingRedirectionAttacksForOtherDomains
{
public static bool CheckURLValid(string url)
{
return Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp);
}
public static bool RedirectUrlIsValid(Controller controller, string redirectURL)
{
if (string.IsNullOrEmpty(redirectURL)) return true;
if (controller.Url.IsLocalUrl(redirectURL)) return true;
var domain = string.Empty;
if (CheckURLValid(redirectURL))
domain = new Uri(redirectURL).Host;
return (controller.HttpContext.Request.Url.Host == domain);
}
public static void RedirectUrlIsValidException(Controller controller, string redirectURL)
{
if (!RedirectUrlIsValid(controller, redirectURL)) throw new UnauthorizedAccessException("URL redirects outside the application domain are not allowed!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment