Fix ReturnUrl When Sharing Forms Authentication with Multiple Web Applications

Scenario: You have two web applications www.mydomain.com and login.mydomain.com. The login site provides a centralized login application and www contains any number of web applications that should use the auth ticket issued by the login site.

The auth ticket can be setup to be shared across the two 3rd level domains no problem. The problem with this setup is that when the user requests a page on www and gets redirected to login the ReturnUrl query string parameter contains a relative path. As far as I know there are not any extensibility points on the FormsAuthenication or FormsAuthenticationModule classes that you can use to fix this. A quick and dirty fix is to use the EndRequest event in your global.asax like this:

 

   1:      protected void Application_EndRequest(object sender, EventArgs e)
   2:      {
   3:          string redirectUrl = this.Response.RedirectLocation;
   4:          if (!string.IsNullOrEmpty(redirectUrl))
   5:          {
   6:              this.Response.RedirectLocation = Regex.Replace(redirectUrl, "ReturnUrl=(?'url'.*)", delegate(Match m)
   7:              {
   8:                  string url = HttpUtility.UrlDecode(m.Groups["url"].Value);
   9:                  Uri u = new Uri(this.Request.Url, url);
  10:                  return string.Format("ReturnUrl={0}", HttpUtility.UrlEncode(u.ToString()));
  11:              }, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  12:          }
  13:      }

The basic idea is to intercept the redirect and process the returnurl query string parameter with a regex. This could also be wrapped up in it's own HttpModule. It's kind of cheezy I know but it seems to work.

Published Tuesday, February 6, 2007 11:01 AM by findleyd
Filed under:

Comments

# re: Fix ReturnUrl When Sharing Forms Authentication with Multiple Web Applications

Monday, February 1, 2010 1:09 AM by Gerardo Diaz

Thanks very much for your code.

# re: Fix ReturnUrl When Sharing Forms Authentication with Multiple Web Applications

Thursday, July 8, 2010 11:30 AM by Donnie Hale

Thanks for this - exactly what I was looking for (w/ the minor correction from Max). Note that the code doesn't completely show up with the current overall page layout - it's truncated on the right with no way to scroll over. I had to cut-and-paste the correct pieces from "View Source" to an empty .html page to see the entire code snippet. Thanks again, Donnie.