Search code examples
asp.nethttp-redirectforms-authenticationhttpmodule

HttpModule endless redirect


I'm using an HttpModule to try and redirect users to the login page if they're not authenticated, but for some reason it's just endlessly redirecting the page without landing anywhere.

Here's the module:

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

public class AuthenticationModule : IHttpModule
{
    public AuthenticationModule()
    {            
    }

    public string ModuleName 
    { 
        get
        {
            return "AuthenticationModule";
        }
    }

    public void Init(HttpApplication app)
    {
        app.BeginRequest += (new EventHandler(Application_BeginRequest));
    }

    private void Application_BeginRequest(object source, EventArgs e)
    {
        HttpApplication app = (HttpApplication)source;
        HttpContext context = app.Context;
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;

        if (!request.IsAuthenticated && !request.RawUrl.Contains(FormsAuthentication.LoginUrl))
        {
            FormsAuthentication.RedirectToLoginPage();
        }
    }

    public void Dispose() { }
}

I don't recall having ever worked with HttpModules before, so I'm not sure what's not working.

How can I fix this?


Solution

  • request.RawUrl is the URL I entered into the browser. Your check request.RawUrl.Contains(FormsAuthentication.LoginUrl) is case sensitive.

    Additionally there are no checks for ressources. So each request for images, css files etc. will redirect to login page. You need to check if authentication is required for the ressource being called.

    Edit (hit the save button to early)

    Additionally I would do it on AuthenticateRequest