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
Related
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 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?
I'm new in ASP.NET and already got a lot of answers here searching on google (THX!).
My task is now to build a website, where authentication is required, so I choosed form based authetication, which is working well.
I need to add functionality, when user can click on link and after redirecting to that website he will get automatically authorized based on GET parameters.
For example:
http://www.mysite.com/login.aspx?username=xxx&password=yyy
So after clicking on such link he will skip login page and continue to page behind.
Could you please help me with that question?
P.S. I'm aware, that it is not secure and username with password will be visible as clear text, but here we are talking about generated username and password which will be available just for one day and it is required to identify user to do one request.
You could do something like.
Make sure the username and password are in the querystring, and then assign them to a username and password varaible.
c#
if (FormsAuthentication.Authenticate(username, password))
{
FormsAuthentication.SetAuthCookie(username, true);
FormsAuthentication.RedirectFromLoginPage(username, true);
}
else { // not authenticated. do something }
vb.net
If FormsAuthentication.Authenticate(username, password) Then
FormsAuthentication.SetAuthCookie(username, true)
FormsAuthentication.RedirectFromLoginPage(username, true)
Else
' not authenticated. do something.
End If
For this to work you will need to import/using System.Web.Security. The true value tells your authentication to set a persistent cookie value.
If you are using SQL Server as the database, the easiest way is to use ASP.NET membership provider. By using that you will be able to authenticate user in an effective way. Here you can use Aspnet_regsql.exe to create required batabase tables. There is a good explanation about Creating a Web Site with Membership and User Login
Hope this will help
how to auto login the user like in facebook.
what i mean that if the user ticks remember me then next time he will be auto logged in
thanks
How websites like Facebook do it is by storing a cookie on the users computers/browser. Which stays there until it is deleted or expires. When the user then visits the Website your code will read the data from the cookie and authenticate based on that information. You could be storing a Token for example which you save to a database so your can see that it represents the user, this is just a idea. Just to be safe you should maybe also consider encrypting the data in the Cookies. Be careful about just reading Cookie's, they are easy to change and can give you some serious security problems.
So it depends if your rolling your own custom authentication, in which case you need to create the cookie and check for it. Or if your using ASP.NET FORMS for authentication in which case you can look here - How to get the asp.net login control to auto authenticate a previously authenticated user?
Use a persistent cookie (or HTML5 local storage like Stack Overflow does) to store some reference so that you know who has authenticated in your back end.
You need to set a cookie when the user logs in and set its expiration time in the future. Until the time elapses, your application would recognize the user.
I'm making the assumption you'll be using Forms Authentication.
If so, take a look at the System.Web.Security.FormsAuthentication class.
Specifically - these two static methods:
bool Authenticate(string username, string password)
void SetAuthCookie(string username, bool createPersistentCookie)
Setting the createPersistentCookie to true will persist the session cookie across browser sessions.
I'm trying to get forms authentication working for an mvc site. I have a custom database with a users table, and I would like to do my own password validation.
I am logging in my user like this:
if (PasswordHasher.Hash(password) == dataUser.Password)
{
FormsAuthentication.SetAuthCookie(email, true);
return true;
}
The problem is, when the session expires obviously the user has to login again.
I am thinking I should be storing this Auth cookie in my users table?
Update: I'm obviously in desperate need of more education in this area. I just noticed that the user stays authenticated even after an iisreset.
I guess what I'm asking is how can I get persistent and non persistent authentication working properly. I want a user to not have to login again if they click "remember", and if they don't then their authentication should expire when the forms authentication is set to expire.
Turns out I forgot to put my variable in the second argument of the SetAuthCookie method. It was always sending true for the "persistent" argument. FML.
I'd recommend implementing a custom Membership Provider so you can leverage the existing controls or patterns that are out there for the existing membership providers.