Check ReturnUrl is valid before redirecting

asp.netasp.net-membership

I'm using ASP.NET Membership and Form Authentication and before redirecting to the returnURL I wanted to validate it. For those unfamiliar with the workflow, basically if you request a page that requires that you are authenticated, you are redirected to a login page. In the URL string you'll see a parameter called returnURL, e.g.
http://example.com/login.aspx?ReturnUrl=%2fprotected%2fdefault.aspx

Whether you use this in a redirect such as Response.Redirect(returnURL) or indirectly through the FormsAuthentication.RedirectFromLoginPage method, it passes without validating returnURL. FormsAuthentication.RedirectFromLoginPage does have a security check that it is isn't leaving the domain, but that still doesn't stop someone from putting enough random characters to cause an error.

I tried using System.IO.File.Exists(Server.MapPath(returnURL)) but given enough illegal characters it cause Server.MapPath to error.

Note: URLEncoding doesn't work because we are not cleaning a parameter, but the primary URL.

Any other suggestions for validating or cleaning the returnURL value?

Best Answer

This post explains the anatomy of the ReturnURL http://blogs.msdn.com/vijaysk/archive/2008/01/24/anatomy-of-forms-authentication-return-url.aspx

As you rightly state, the domain is checked, so along with encrypting your authentication cookie, and ensuring you use https I think the only thing you can do to to stop an invalid ReturnURL is to just ignore it, and redirect all logins to the home page or top level of you site letting users then navigate back via the menu. A good example of this is when you log into hotmail.

Related Topic