Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly handle ReturnUrl when using UrlRewrite in ASP.NET 2.0 WebForms

I have a folder with multiple .aspx pages that I want to restrict access to. I have added web.config to that folder with <deny users="?"/>.

The problem is that ReturnUrl is auto-generated with physical path to the .aspx file while I'm using UrlRewrite.

Is there a way to manipulate ReturnUrl without doing manual authentication check and redirection? Is there a way to set ReturnUrl from code-behind or from web.config?

EDIT: The application is using ASP.NET 2.0 WebForms. I cannot use 3.5 routing.

EDIT 2: It seems like 401 status code is never captured. It returns 302 for protected page and redirects to login page with ReturnUrl. It does not return 401 for protected page. Hmm... Interesting... Ref: http://msdn.microsoft.com/en-us/library/aa480476.aspx

This makes things harder... I might have to write reverse rewrite mapping rules to regex match ReturnUrl and replace it if it doesn't return 401... If it does return 401 I can either set RawUrl to Response.RedirectLocation or replace ReturnUrl with RawUrl.

Anyone else have any other ideas?

like image 753
Brian Kim Avatar asked Oct 26 '22 23:10

Brian Kim


1 Answers

Check it out. Hope this helps.

#region [ Imports ]

using System;
using System.Web;
using System.Web.Security;

#endregion

namespace Foo.Handlers
{

    public class AuthModule : IHttpModule
    {

        #region IHttpModule Members

        public void Init(HttpApplication application)
        {
            application.PostReleaseRequestState += delegate(object s, EventArgs e)
                {
                    if (application.Response.StatusCode == 401)
                        application.Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(application.Request.RawUrl), true);
                };
        }

        public void Dispose() { }

        #endregion

    }

}

<modules>
  <add name="AuthModule" type="Foo.Handlers.AuthModule, Foo"/>
</modules>
like image 142
Mehdi Golchin Avatar answered Oct 28 '22 13:10

Mehdi Golchin