views:

267

answers:

0

Hello everyone..

I have a problem with URL rewriting and Forms authentication in ASP.NET... Based on articles I've found on the net, I have created the following HttpModule:

public class UrlRewriter : IHttpModule
{
    private UrlRewriteConfigurationSection config;

    public UrlRewriter()
    {
        config = ConfigurationManager.GetSection("urlrewrites") as UrlRewriteConfigurationSection;
    }

    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        httpApplication.AuthorizeRequest += new EventHandler(OnAuthorizeRequest);
    }

    private void OnAuthorizeRequest(object sender, EventArgs e)
    {
        string requestedPath = HttpContext.Current.Request.Path;

        foreach (UrlRewriteRule rule in config.UrlRewriteRules)
        {
            RegexOptions options = config.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;

            Regex regex = new Regex(rule.UrlPattern, options);
            Match match = regex.Match(requestedPath);

            if (match.Success)
            {
                string newPath = regex.Replace(requestedPath, rule.RewritePattern);
                if (!String.IsNullOrEmpty(newPath))
                {
                    HttpContext.Current.RewritePath(newPath);
                    return;
                }
            }
        }
    }
}

The problem, however, is that this somehow disables authorization! To explain assume i have the following rewrite rule:

UrlPattern: ^user/profile$ RewritePattern: protected/profile.aspx

And assume that the folder protected is setup to deny anonymous users access..

Now, when the code in the OnAuthorizeRequest runs, it correctly rewrites the path to protected/profile.aspx, however, the problem is that I am shown the page, even though I'm not logged in! If I request the page directly (http://localhost/site/protected/profile.aspx) it does not allow access to the site..

All articles I find on the net says I need to do the rewrite in AuthorizeRequest as opposed to AuthenticateRequest or BeginRequest..

Any ideas?

N.B.: I have tried moving my rewriting code to AuthenticateRequest which does seem to work, but redirection to the login page is not correct (e.g. it redirects to /login?returnUrl=protected/profile.aspx instead of login?returnUrl=user/profile)