views:

217

answers:

2

Using Forms Authentication, I am storing a cookie for each user if they mark Remember Me during login, using the following piece of code in the Login1_LoggedIn event.

if (rememberMe.Checked) FormsAuthentication.SetAuthCookie(Login1.UserName, true);

When the user arrives on my page with a cookie, I need to get his/her user name so I can check their roles. Does the Forms Authentication cookie store this information, and how can I retrieve it?

+1  A: 

The string you parse to SetAuthCookie (Login1.UserName in your case) will be stored in the IPrincipal when the user accesses a page. You can access it using:

Page.User.Identity.Name
David G
The problem with this is that when I check for the cookie, the user is not logged in; therefore his identity is not established, and consequently I cannot use this code.
Matthew Jones
Haha. Ignore my last comment. Silly me for jumping to conclusions. +1 and Accepted for DaveG!.
Matthew Jones
It's also possible to store user roles in the authentication cookie itself and use Page.User.IsInRole("yourrole");
David G
+1  A: 

Try

Page.User.Identity.Name

or

HttpContext.Current.User.Identity.Name
Kristoffer Deinoff
+1 cause this is correct, but DaveG beat ya so he gets accepted. Still, thanks!
Matthew Jones