Forms-Based Authentication

for RuBoard

The previous discussion is relevant for intranets or other scenarios where users will have Windows user accounts on the servers or domains. Furthermore, Windows Integrated Security does not work across firewalls or proxies. For public Web sites we need another approach.

The alternative approach is to bring up a login form to authenticate the user. We will look at two of the several approaches to login forms that are possible within .NET. Step 0 of the FormsBasedAuthentication example uses the .NET FormsAuthentication class and the config.web file. Step 1 of the example uses a database login to illustrate using an external database.

Forms Authentication and Authorization

.NET Forms-based authentication uses web.config , login form, and a cookie to authenticate the user. [16] Typically in this scenario you will set up the Web site for anonymous access so that no users will be screened out by IIS. Here is the web.config file section for the Step 0 example:

[16] You do not have to use a cookie, but it is used for automatic authentication.

 <authentication mode="Forms">       <forms name = "HotelBrokerCookie" path="/"                      loginUrl="Login.aspx"                      protection="All" timeout="10">         <credentials passwordFormat=Clear>           <user name="Natasha" password="Natasha" />           <user name="Adams" password="Adams" />           <user name="peter" password="peter" />         </credentials>       </forms>    </authentication>    <authorization>      <allow users="Natasha,peter" />      <deny users="*" />    </authorization> 

The authentication mode is set to Forms. This means that the User.Identity object will be a FormsIdentity instance if the user is authenticated. The forms element has several attributes that define how the authentication is set up. The name attribute is the name of the cookie. The path attribute indicates where on the site the cookie is valid; "/" indicates the entire site. The loginUrl indicates where the login form resides. The protection attribute indicates how the cookie should be encrypted. "All" indicates that the cookie should be validated and encrypted. Other options are None, Encryption, and Validation. Timeout indicates the number of minutes before the cookie becomes invalid ( expires ).

The credential elements indicate how the password should be stored in the configuration file. For simplicity we have used clear text. You could also specify SHA1 or MD5 to encrypt the passwords. [17] If passwords are stored in web.config , it should be secured against download (which is the default). Passwords for the configuration file can be encrypted with the static FormsAuthentication method HashPasswordForStoringInConfigFile . [18]

[17] These encryption formats are discussed in Chapter 7.

[18] Storing passwords in a configuration file is convenient for development and testing work. If you do your own validation, as we do with the database example, you do not need to use the web.config file.

The user elements indicate the user names and passwords. The authorization section, as discussed earlier, determines which authenticated users are authorized to access the Web site.

Since this example uses redirection and cookie validation, a user should attempt to access the main page, http://localhost/ FormsBasedAuthenticationStep0/default.aspx , instead of the login.aspx file. If a valid cookie does not exist on the system, the user will be sent to the login page. If a valid cookie exists, it will be used to validate the user. If the user is validated, they will go straight to the default.aspx page. If users went straight to the login page, they would have to log in every time, even with a valid cookie.

Here is the code for handling the Login button event:

 private void Login_Click(object sender, EventArgs e)  {    if (FormsAuthentication.Authenticate(txtUserId.Text,      txtPassword.Text))    {      FormsAuthentication.RedirectFromLoginPage(txtUserId.Text, true);    }    else    {      lblErrorMessage.Text = "Could not authenticate user.";    } 

For simplicity, the Password text box does not hide the password. A password text box that hides the password was discussed in Chapter 10.

The FormsAuthentication class's Authenticate method validates the user name and password from the web.config file. If a valid cookie was on the system, the user is not redirected to the login page. RedirectFromLoginPage creates a cookie, and redirects the user to the default.aspx page. If the second argument is true, a persistent cookie is placed on the user's system. Persistent cookies are a security risk, because the cookie can be stolen as it is transmitted (hijacked). You should use SSL to protect the cookie. You can remove the session or persistent cookie with the SignOut method. The check of the authorization section of web.config to see if the user has the rights to access the page is done on each request.

If you run the Step 0 example only Natasha, peter, and Adams will be authenticated. However, only Natasha and Peter will be authorized to use the site. Of course, only Natasha will be found in the database of Acme customers. That test has been moved to default.aspx to distinguish it from the forms authentication done in login.aspx.

Default.aspx can refer to the name of the user through the User object. The type of identity object is FormsIdentity .

 bool ok = HotelState.acme.Login(User.Identity.Name); 

If you succeed and log in as Natasha once, subsequent tries will succeed without the login page because we have created a persistent cookie. To avoid persistent cookies, set the second argument to RedirectFrom LoginPage to false .

The application, however, runs under the identity of the system process or thread, not the identity of the user name that is logged in. Hence, if you want to use role-based security in ASP.NET with Forms authentication, you will have to create your own roles by using a GenericPrincipal .

Database Login Validation

It is fairly straightforward to add password validation against a database as in Step 1 of the FormsBasedAuthentication example. When a user is registered, the password is hashed and is stored in the Acme database. [19]

[19] This assumes that you do not have to mail the password to a user that has forgotten it. Then you have to use two-way encryption.

 string password =     FormsAuthentication.HashPasswordForStoringInConfigFile            (txtPassword.Text, "MD5");  bool ok = HotelState.acme.Register(txtUserId.Text,            password, txtFirstName.Text, txtLastName.Text,            txtEmailAddress.Text); 

Before logging in, the password is again hashed and compared with the version stored in the database.

 string password =     FormsAuthentication.HashPasswordForStoringInConfigFile             (txtPassword.Text, "MD5");  bool ok = HotelState.acme.Login(txtUserId.Text, password); 

With this approach you would have to maintain your own data store to track who is or is not a hotel administrator in order to decide who can see the hotel administration page.

for RuBoard


Application Development Using C# and .NET
Application Development Using C# and .NET
ISBN: 013093383X
EAN: 2147483647
Year: 2001
Pages: 158

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net