15
votes

In an ASP.NET (2.0) application I use FormsAuthentication.

In the Global.asax / Application_AuthenticateRequest method I check if HttpContext.Current.User is null.

Is this enough to know if the forms authentication cookie exists, the ticket is not expired, and overall, that the forms authentication mechanism has done its job to validate the user?

I need this, because I have certain pages in that application, which sometimes do not need authentication to be accessed (based on some criteria), and I put them in a separate "location" directive in web.config with in order to exclude them from "catch all" forms authentication.

I.e. I'm trying to check in Application_AuthenticateRequest if the page accessed in this "location" needs protection or not, and if yes, to know if the user have been authenticated already, or I need to redirect to Logon.

EDIT: As the answers suggest, most probably I'll go with IsAuthenticated. In order for me to grasp it better, here are 2 bonus questions :) (please, edit other answers to add these, thanks) :

  1. Can I assume that if IsAuthenticated is true, then HttpContext.Current.User will for sure contain the username for the authenticated user?

  2. How can I end up with an "anonymous user" in HttpContext.Current.User, if FormsAuthentication is enforced, and only few pages are excluded with "location" directive?

4
I prefer it when the user's credentials are the only deciding factor in authorizing access to a resource. Perhaps you could split the functionality into two different pages and allow ASP.NET to handle the security?Greg

4 Answers

29
votes

No, the User could just be a reference to the anonymous user. Check HttpContext.Current.Request.IsAuthenticated.

3
votes

I usually use Request.IsAuthenticated. I couldn't tell you whether your approach should work or not. It sounds like it should, although it might have side effects if you support anonymous logins?

1
votes

Good question: in addition to the answers others have given, I'd suggest that you take a look at this article on the 4GuysFromRolla site.

1
votes

As an aside, be sure to check the context is not null as well (incase your working in an httpmodule).