Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request.IsAuthenticated is never true

I've got an HttpModule implemented that's supposed to restrict access to the /courses/ directory of my site, but there's one major problem with it.

Request.IsAuthenticated is always false.

Here's the code:

using System;
using System.Web;

public class CourseAuthenticationModule : IHttpModule
{
    public void Dispose() { }

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

    public void BeginRequest(Object source, EventArgs e)
    {
        HttpApplication app = (HttpApplication)source;
        HttpContext context = app.Context;
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;

        if (request.Path.ToLower().StartsWith("/courses/") 
            && !request.IsAuthenticated)

        {
            response.Redirect("/");
        }
    }
}

I have no idea why this happens, but the condition will always evaluate to true when accessing the /courses/ directory.

Edit:

I found this in the Web.Config. Not sure if it's relevant.

<authentication mode="Forms">
  <forms loginUrl="userlogin.asp" name=".cc" protection="All" path="/" timeout="2880" slidingExpiration="true" />
</authentication>

Am I doing something wrong? How can I fix this?

like image 504
keeehlan Avatar asked Sep 30 '22 16:09

keeehlan


1 Answers

The BeginRequest as the first event is too early to ask if the user is authenticated or not.

At that point you can simple check if its authenticated by direct read the cookie as:

string cookieName = FormsAuthentication.FormsCookieName;    
HttpCookie authCookie = Context.Request.Cookies[cookieName];

if (null == authCookie || FormsAuthentication.Decrypt(authCookie.Value) == null)
{
    // is not authenticated
}
like image 115
Aristos Avatar answered Oct 05 '22 09:10

Aristos