Forms Authentication - Storing and Retrieving User Names - asp.net

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?

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

Try
Page.User.Identity.Name
or
HttpContext.Current.User.Identity.Name

Related

What to call after validateUser() for forms authentication?

I made a custom membership provider and overrode the ValidateUser method, but now I am confused. I am not using any Login controls, I just have a site wide login (username and password box) on a masterpage.
Questions:
Do I need to call the ValidateUser() method myself? If so, what are
the next steps to take? Do I create the auth cookie which methods do I need to call to complete the login?
I need to return some custom user data if the user is authenticated. Is it better to
call GetUser and check for null or just call ValidateUser and then
grab a user object?
Where and how should I store the custom data for the user? Is it stored in the identity object? Should I store it in the MembershipUser Object?
Yes, you verify that the credentials are correct by doing a call such as
Membership.ValidateUser(TextBoxUsername.Text, TextBoxPassword.Text)
If the above call returns true then you need to set the authentication cookie like so:
FormsAuthentication.SetAuthCookie(TextBoxUsername.Text, CheckboxRememberMe.Checked);
There I used a "remember me" checkbox if you want to login automatically next time.
To get the user details you can call
Membership.FindUsersByName(TextBoxUsername.Text)
The most handy place you can store the user details is the session.
You didn't ask, but just as important would be a log out page. The functionality needed to undo the login steps are:
FormsAuthentication.SignOut();
Session.Abandon();
Response.Redirect("~/login.aspx", false);//or homepage, or any other page

How ASP.NET form authentication works: recognising cookies from request

I am reading on form authentication in ASP.NET and cannot understand some moment:
James enters a username-password, they are saved in the db. A cookie from username is created, encrypted and attached to a response. As I understand then, when we get a request we need to recognise that cookie received are from James and so we can show his customised page.
What I would like to understand is how system will retrieve username form cookie and then load his info from db?
Forms Auth is storage agnostic. It doesn't have to use a database, indeed you can use it with usernames and passwords in web.config.
So what happens is
A user logs in.
The user is authenticated against the membership provider (which can use SQL, Active DIrectory, web.config, Oracle, MySQL, whatever)
A forms authentication token is created for the user, and is placed on the user machine via a cookie.
Each subsequent request reads the forms authentication token, and queries the provider to get the user details.
The user details are used to populate the user identity in the HttpContext and current thread for the request which is then available to your code to use.
In your code you can check the User property in the Page class (WebForms) or the User property in the controller class (MVC).
While you can get at it via the current thread, or the current context it's not advised, especially once you start using background tasks, where the identity may not propagate to the thread, or the context may change.
You'll note that nothing is stored in a database when the user logs in. It's all in the forms authentication token, and the work of retrieving the user from it's store on each request is done for you.
Afaik Forms Authentication does not store or load anything in any database. You can use a database to store the username and password, or you can put them in the web.config. How you store user credentials and validate them is up to you, and can happen separately from Forms Authentication.
Once you have validated a user (against database or some other logical storage), you use FormsAuthentication to write the authentication cookie. You do not need to worry about decrypting the cookie.
You can get the username from System.Threading.Thread.CurrentPrincipal.Identity.Name. To retrieve user's info from the database, you would query the database using the value if the principal identity name.
Response to comments
Right, you can use forms authentication with the membership provider, active directory, or your own custom user database. FormsAuth doesn't care about the password at all, unless it is stored in web.config (as noted in blowdart's more complete answer). It just writes the cookie, which is decrypted and used to create the thread identity automatically.
Additional Info
Even though this was marked as the answer, blowdart's response is much more complete. You really should not get the identity from the thread if you need it in an ASPX page or MVC controller, use the properties he referenced.
You get the username in your web form by calling User.Identity.Name, e.g. like this:
protected void Page_Load(object sender, EventArgs e)
{
string userName = User.Identity.Name;
}
ASP.NET interprets the cookie for you, you don't have to read it yourself. Or is your question how to store the user and password in the DB?

How can I tell what the username is of an authenticated using Forms Authentication with ASP.NET

After a user is authenticated I store their username in session state but if the session times out, I want to create a new session for the user based on their username they authenticated with original. How can I get from Forms Authentication the currently authenticated user?
The current authenticated user should be the name in the IIdentity assigned to the identity of the IPrincipal on the User property of the HttpContext
HttpContext.Current.User.Identity.Name
In ASP.NET MVC, it is available in a controller via
this.User.Identity.Name
You don't need to store the user name in session at all - in your page simply access the User property of HttpContext. To get the actual username you would use User.Identity.Name, and as a handy short cut the ASP.NET Page class itself has a user property, so you could do
string userName = Page.User.Identity.Name;
in your code behind.
If you're using ASP.NET MVC there's a User property you can access in a controller
string userName = User.Identity.Name

Login modes other than forms authentication is ASP.NET

Am trying to design login page for my website and I am looking for methods other than forms authentication. The way in which I am trying is to have a table in the database that stores user information and check for the user validity.
The point where I get struck is how do i set cookies and session variables and how will I carry it through out the system. Can anyone tell/suggest me where I can relevant material so as to move forward. And also is my idea of negating traditional forms authentication and going for a model I described, is it good also does any other better method exist?
You can do this even with forms authentication itself...
For Forms Authentication to work, you need not have to use the Complete Database Setup that MS uses to Authenticate. You can simply have your own Database and Validate a user yourself, and just set the cookie.
String UserName = "CoolGuy";
String PassWord = "Pwd"
Boolean isValidUser = YourClass.YourMethod(UserName, PassWord);
if (isValidUser)
{ FormsAuthentication.setAuthCookie(UserName, false); }
This will authenticate the user "CoolGuy" for the session, provided YourMethod returns true. And you need to put this code only in Login Page... and the user will automatically be authenticated for the entire session or whatever...
Please see my response to another similar question here... ASP.NET access controls

when is user authenticated when using asp.net CreateUserWizard

I am using the asp.net CreateUserWizard and I have LoginCreatedUser=true. I also have the "OnCreatedUser" property for the CreateUserWizard control to a method and thought the auth ticket would be created at that point but it is not.
When exactly is the authentication ticket (Request.Cookies[".ASPXAUTH"]) populated?
I need to know so that during registration I can modify the UserData and add it to the auth ticket.
I've done this before doing the following:
In the CreateUserWizard_CreatedUser event you know for a fact the user is created, so save the username to HttpContext.Items array.
Check for the username in HttpContext.Items in the page's PreRender() event (it'll run after the CreatedUser() step). If it's there overwrite your authentication ticket
To test this make sure you later decrypt the authentication ticket and check the UserData. In my own projects this is how I handle having a user logged in at registration and have some of their info injected into the auth ticket's UserData.

Resources