Forms Authentication understanding context.user.identity

The way your code is written logins will persist across browser sessions. It might help to understand the basics of what is going on.

For cookie based authentication methods, there are really three actions:

1) Login – validates user’s credentials and creates and stores a cookie on their browser.

2) Logout – simply removes the cookie from the browser (by expiring the cookie or deleting it)

3) Per Request Validation (the part that is is your Application_AuthenticateRequest) – check to see if a cookie exists, and if so, get the user’s Identity and Roles and set HttpContext.Current.User.

Typically, the FormsAuthentication module hides most of this from you. It looks like your code is trying to use some of the elements of FormAuthentication (like the FormsAuthenticationTicket and FormsIdentity. This is fine as long as you get what you want.

Your Login_Authenticate method looks fine EXCEPT you are setting an expiration on the cookie. This will make the cookie persist even if you close and reopen the browser. Since this is not the behavior you want, I would not set a cookie expiration. Setting this is like checking the “remember me” checkbox.

The code in Application_AuthenticateRequest gets run every time a page is served from your application. It’s primary job is to set HttpContext.Current.User. Typically, if no user is logged in, User is either null or an Anonymous user. If a user is logged in, this should represent your user.

If you are doing these three things, then anywhere in your code you can reference HttpContext.Current.User to decide what level of information you want to display. For instance, if you want to restrict a page to administrators only, you could call HttpContext.Current.Users.IsInRole(“Administrators”), and redirect them away from the page if the call returns false.

Hope this helps.

Leave a Comment