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?
Related
I'm writing my first Symfony2 app after a few years with Symfony and am having trouble converting our user management code. It seems that to fit in with Symfony2's authentication model I have to provide user details including their (encrypted) passwords. We authenticate via a webservice that takes the username and password and responds with a confirmation and user level (user, admin etc), but it never sends the real password back to us.
What I want to do is accept the login details from a form, confirm they are valid and then set the user's roles according to the webservice's response. Where do I start?
You need to use a custom authentication provider to authenticate against your webservice. It is explained quite clearly in this blog post
You can create an user provider and its loadUserByName you can call the webservice. If success return the new UserInterface object with the password of the form empty salt string and the roles returned by the service. Also set encoder of the UserInterface to plaintext in security.yml. And then set the new created user provider in form_login auth provider in the firewall.
I am developing an ASP.NET website. I am planning to use Forms authentication in order to guarantee authentication/authorization, but I am facing two problems regarding the authorization:
I know how to set in the web config that the authenticated users are allowed to visit a webpage (say myPage.aspx). But I do not know how to define that UserA is able to access myPage to retrieve his information, not UserB's information.
I was thinking about generating a token when the user authenticates, so I am able to check to whom this token belongs to and verify if this information is available to him.
What do you think about this approach? Does the Form Authentication generates a token like that? (I couldn't find any mention about it in my research). If not, could I adapt the Form authentication mechanisms in order to generate or would I need to write everything on my own?
I would like to access webservices, and these should only return information if the user is logged. For this reason, I would like to use the same token explained above. What do you think about it? Is it a good approach?
I am asking this because I have no experience on designing authentication/authorization mechanisms, any help/hint would be appreciated.
Regarding question one, after forms authentication occurs in an ASP.Net web forms app, the user's identity is exposed as a FormsIdentity object in the Page.User.Identity property. This object has a Name property which contains the username that a user use to log into your site. You can use this value to restrict what a user can access. For example, let's say you have a table in your database with user information containing the following fields:
userId int
userName varchar(25)
...more fields containing user information...
You can restrict a user to only access information from the row in this table in which the userName equals the Page.User.Identity.Name property, either directly if you are using direct ADO.Net or via your query to your ORM-mapped (i.e. nHibernate or EF) domain object.
Regarding question two, the FormsIdentity object exposed by Page.User.Identity has a boolean "IsAuthenticated" property. You can use this to restrict access to your web service as follows:
if(Page.User.Identity.IsAuthenticated)
{
//Call your web service in a secure manner
}
I want to know more about win32 LogonUser api function. The last parameter is a token which can be used to impersonate a windows identity to execute code on a person's behalf. Say I have a login page where I enter my username, password and domain. When the user submits the page I validate the user by making a call to LogonUser() and get a token reference.
I am thinking why not store the token in a cookie and use it at a later stage (perhaps in another page). I just don't know what issues I might have to face upfront...
Can the token expire even if we don't close it properly using the CloseHandle() win32 call? Is there any article related with this particular requirement?
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
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