views:

1312

answers:

4

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?

+2  A: 

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?

Kevin Pang
+12  A: 

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

bdukes
Thanks. I got the idea to use the "standard" way, but just as a side question - how could it be "anonymous" user?
Sunny
If the website allows for anonymous access (meaning not even Basic Authentication is used) then the user is considered anonymous. IIS typically assigns a "user" when somebody arrives in this manner, but it is set to the IUSR_MachineName or something else.
Dillie-O
+1  A: 

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.

Mark Brittingham
A: 

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

ccook