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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With