Last active
January 31, 2019 20:11
-
-
Save pedrovasconcellos/2192824a0739c0a5934397f56df2bce2 to your computer and use it in GitHub Desktop.
Preventing redirection attacks for other domains (C #)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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