This module is used in:
• Create a web application that authenticates user authentication with Forms authentication with Forms. • Use the password hash safely stores and verifies user credentials.
Applicable to:
This module is suitable for the following products and technologies:
• Microsoft Windows_ XP or Windows 2000 Server (with Service Pack 3) and Higher Versions • Microsoft .NET Framework Version 1.0 (with Service Pack 2) and later • Microsoft Visual Studio_ 1.0 .NET development system and higher Version • Microsoft Visual C # _ .NET Development Tools • Microsoft SQL ServerTM 2000 (with Service Pack 2) and later
How to use this module
To maximize this module:
• There must be experience in using Visual C # .NET and Visual Studio .NET. • There must be experience in developing web applications using ASP.NET. • There must be experience in using SQL Server and create SQL Server tables. • There must be experience in accessing SQL Server using ADO.NET. • An instance of SQL Server that can be used to test applications - This instance should not be a production system. • Read the module "Data Access Security". This module provides detailed information about protecting database access, creating, and storing passwords and protection to prevent SQL injection attacks. • Read "How to Use DPAPI (Machine Store" from ASP.NET. This module provides details about how to securely store SQL Server connection strings using DPAPI. • Read "How to Create GenericPrincipal Objects with Forms Authentication". This module provides a detailed description of a Forms authentication ticket for constructing a user role detail.
This page
Summary Preliminary Knowledge Create a web application with login page Configuring a web application for Forms authentication developing students to have haveh and salt values Functions Creating a User Account Database Using ADO.NET to store account details in the database according to database Perform authentication test applications other resources
Summary
ASP.NET FORMS Authentication allows users to enter credentials (usernames and passwords) to Web Form to identify their identity. When these credentials are received, the web application can check these credentials based on the data source to authenticate the user.
This module describes how to secure user credentials in SQL Server using password hash and how to authenticate users according to the account database contained in SQL Server.
Back to top
Preparatory knowledge
Safely store user credentials contain two key concepts:
• Store the password summary. For security consideration, please do not store the password clear text in the database. This module describes how to create and store a unidirectional hash of the user password rather than a password itself. If you want to store encrypted user passwords, it is recommended to select this method because it avoids key management issues related to encryption technology. In order to increase security and reduce the threat related to dictionary attacks, the methods described in this module combine SALT (random number generated by encryption mode) with passwords before creating a password hash.
• An important thing that does not store passwords in the database is that once the user forgets the password, it cannot be recovered. Thus, the application should use a password prompt and store them with the password summary in the database. • Verify user input. When the user input is passed to the SQL command, such as comparison statements or strings in the pattern matching statement, you should be careful to verify this input to ensure that the final command does not include syntax errors, and make sure that hackers will not make your The application runs any SQL command. The username provided in the login process is particularly important, because the application's security model is fully authenticated to the user correctly and safely. For more information on verifying the user input of the SQL command and the verification function, see "SQL Injection Attacks" in the module "Data Access Security". Back to top
Create a web application with a login page
This process creates a simple Visual C # web application that contains a user who can enter a username and password login page.
To create a web application with a login page, perform the following steps:
• Start Visual Studio .NET and create a new Visual C # ASP.NET web application called Formsauthsql. • Use the Solution Explorer to rename the WebForm1.aspx to Logon.aspx • Add the controls listed in Table 1 to Logon.aspx to create a simple login form.
Table 1: Logon.aspx Control Control Type Text ID Label User Name: - Label Password - Text Box - TXTUSERNAME TEXT BOX - TXTPASSWORD BUTTON REGISTER BTNREGOSTER button Logon Btnlogon Label - LBLMESSAGE
Your web page should be similar to the page shown in Figure 1.
Figure 1. Login page Web Form
• Set TXTPassword's TextMode property to Password.
Back to top
Configure web applications for Forms authentication
This procedure edits the application's web.config file to configure the application for Forms authentication.
To configure a web application for Forms authentication, perform the following steps:
1. Use the Solution Explorer to open Web.config. 2. Locate to
forms>
authentication>
4. Add the following
Back to top
Developer functions in developing haveh and salt values
This process adds two utility methods to the web application; one method generates a random SALT value, and another creation hash based on the provided password and the SALT value.
To develop a function of a raggy and a SALT value, perform the following steps:
1. Open Logon.aspx.cs and add the following USING statements to an existing USING statement at the top of the file. Using system.security.cryptography;
Using system.web.security;
2. Add the following static methods to the WebForm1 class to generate a random SALT value and return this value as a base 64 encoded string. Private Static String Createsalt (int size)
{
// generate a cryptographic random number using the cryptographic
// service provider
RNGCRYPTOSERVICEPROVIDER RNG = New RNGCRYPTOSERVICEPROVIDER ();
BYTE [] BUFF = New byte [Size];
RNG.GETBYTES (BUFF);
// Return A Base64 String Repesentation of the Random Number
Return Convert.TOBASE64STRING (BUFF);
}
3. Add the following static methods to generate a hash value based on the provided password and the SALT value. Private Static String CreatePasswordHash (String PWD, String Salt)
{
String SaltandPwd = String.concat (PWD, SALT);
String hashedpwd =
FormsAuthentication.hashPasswordforstoringInfigfile (
SaltandPWD, "SHA1");
Return Hashedpwd;
}
Back to top
Create a user account database
This process creates a new user account database in SQL Server, which contains a user table and a stored procedure for querying the user database.
To create a user account database, do the following:
1. On the Microsoft SQL Server Programs menu, click Query Analyzer and then connect to the local SQL Server. 2. Enter the following SQL scripts. Note that "localmachine" at the end of this script must be replaced with its own computer name. Use master
Go
- CREATE A DATABASE for the security information
IF exists (Select * from master..sdatabases where name = 'useeraccounts')
DROP DATABASE USERACCOUNTS
Go
Create Database Useraccounts
Go
Use Useraccounts
Go
CREATE TABLE [Users]
[Username] [varchar] (255) Not null,
[Passwordhash] [varchar] (40) Not null,
[Salt] [varchar] (10) Not null,
ConsTRAINT [PK_USERS] Primary Key Clustered
[Username]
) On [primary]
) On [primary]
Go
- Create Stored Procedure To Register User Details
Create Procedure RegisterUser
@username varchar (255),
@passwordhash varchar (40),
@salt varchar (10)
AS
INSERT INTO USERS VALUES (@Username, @passwordhash, @salt)
Go
- Create Stored Procedure To Retrieve User Details
Create Procedure LookUpuser
@username varchar (255)
AS
SELECT PasswordHash, Salt
From user
Where username = @username
Go
- Add A login for the local aspnet account
- In The Following Statements, Replace Localmachine with your Your
- Local Machine Name
EXEC SP_GRANTLOGIN [localmachine / aspnet]
- Add A Database Login for The Useracts Database for the ASPNET Account
EXEC SP_GRANTDBACCESS [localmachine / aspnet]
- Grant Execute Permissions to the lookuser and registeruser stores
Grant Execute ON LOOKUPUSER TO [LocalMachine / ASPNET]
Grant Execute on RegisterUser to [localmachine / aspnet]
3. Run the query to create a UserAccounts database. 4. Exit Query Manager.
Back to top
Store account details in the database using ADO.NET
This process modifies the web application code to store the username, the generated password hash and the SALT value in the database.
To use ADO.NET to store account details in the database, do the following:
• Return to Visual Studio .NET and double-click the Register button on the Web Form to create a button Click the event handler. • Add the following code to the method. String Salt = CreateSalt (5);
String passwordhash = creagepassword.text, salt);
Try
{
StoreAccountDetails (txtusername.text, passwordhash, salt);
}
Catch (Exception EX)
{
LBlMessage.Text = ex.Message;
}
• Add the following USING statement to an existing USING statement at the top of the file. Using system.data.sqlclient;
• Add the StoreAcCountDetails utility method using the following code. This code is connected to the UserAccounts database using ADO.NET and stores the username, password hash and SALT values in the UserS table. Private Void StoreAccountDetails (String Username, String Password),
String salt)
{
// See "How to use dPapi (machine store" from ASP.NET "for information
// About Securely Storing Connection Strings.
SqlConnection conn = new SqlConnection ("Server = (local);
Integrated Security = SSPI; "
"Database = Useraccounts");
Sqlcommand cmd = new sqlcommand ("registeruser", conn);
cmd.commandtype = commandtype.storedProcedure;
SQLParameter Sqlparam = NULL;
Sqlparam = cmd.parameters.add ("@ username", sqldbtype.varchar, 255);
SqlParam.Value = UserName;
Sqlparam = cmd.parameters.add ("@ passwordhash", sqldbtype.varchar, 40);
SqlParam.Value = PasswordHash;
Sqlparam = cmd.parameters.add ("@ salt", sqldbtype.varchar, 10);
SQLParam.Value = SALT;
Try
{
Cn.open ();
cmd.executenonquery ();
}
Catch (Exception EX)
{
// Code to Check for primary key viology (duplicate account name)
// or Other Database Errors OMIMITTED For Clarity
Throw new Exception ("Exception Adding Account." EX.MESSAGE);
}
Finally
{
CONN.CLOSE ();
}
}
Back to top
Authenticate user credentials according to the database
This process develops ADO.NET code, used to find the username provided in the database and press the matching password hash to verify the provided password.
Note In many forms authentication based on .NET role authorization, you may have to retrieve the role to the user from this database. These roles can then be used to generate GenericPrincipal objects associated with authenticated web requests for .NET authorization.
For more information on the Forms authentication ticket for constructing a user role detail, see "How to create genericprincipal objects with forms authentication".
To verify user credentials according to database, do the following:
• Return to Logon.aspx.cs and add VerifyPassword private helper method, as shown in the following code. Private Bool VerifyPassword (String SupplieduserName, String Suppliedpassword)
{
Bool passwordmatch = false;
// Get the salt and pwd from the database based on the user name.
// See "How to: use dPapi (Machine Store) from asp.net," "How to: use dpapi
// (User Store) from Enterprise Services, "and" How to: Create A DPAPI
// Library "for more information about how to use the dpapi to securely store
// connection strings.
SqlConnection conn = new SqlConnection ("Server = (local);
Integrated Security = SSPI; "
"Database = Useraccounts");
SQLCommand cmd = new sqlcommand ("lookupuser", conn;
cmd.commandtype = commandtype.storedProcedure;
SQLParameter Sqlparam = cmd.parameters.add ("@ username",
Sqldbtype.varchar, 255);
SQLParam.Value = supportusername;
Try
{
Cn.open ();
SqlDataReader Reader = cmd.executeReader ();
Reader.read (); // advance to the one and only row
// Return Output Parameters from Returned Data Stream
String dbpasswordhash = reader.getstring (0);
String salt = reader.getstring (1);
Reader.Close ();
// Now Take the sal and the password entered by the user
// and constnate theme together.
String passwordandsalt = string.concat (SuppliedPassword, SALT);
// now Hash them
String hashedpasswordwordsalt =
FormsAuthentication.hashPasswordforstoringInfigfile (
Passwordandsalt, "SHA1");
// Now verify.
PasswordMatch = hashedpaals (dbparswordhash);
}
Catch (Exception EX)
{
Throw new Exception ("EXECPTION VERIFYING Password." ex.Message);
}
Finally
{
CONN.CLOSE ();
}
Return PasswordMatch;
}
Back to top
Test application
This process will test the application. You will register a user, which causes the username, the password hash and the SALT value being added to the UserArge table of the Useraccounts database. Then log in as the same user to ensure that the password verification routine performs the correct operation.
To test an application, do the following:
1. Return to the Logon Form and double-click the Logon button to create a button Click the event handler. 2. Add the following code to the Logon button Click the event handler to call the VerifyPassword method and display the message according to whether the username and password are valid. Bool passwordverified = false;
Try
{
Passwordverified = verifypassword (txtusername.text, txtpassword.text);
}
Catch (Exception EX)
{
LBlMessage.Text = ex.Message;
Return;
}
IF (Passwordverified == True)
{
// the user is automated
// at this point, an Authentication Ticket IS NORMALLY CREATED
// this can subssequently be used to generate a genericprincipal
// Object for .NET Authorization Purposes
// for Details, See "How to: use forms authentication with genericprincipal
// Objects
LBLMessage.Text = "Logon Successful: User is Authenticated";
}
Else
{
lblMessage.Text = "Invalid UserName Or Password";
}
3. On the Build menu, click BuildSolution. 4. In the Solution Explorer, right-click Logon.aspx, and then click View in Browser. 5. Enter your username and password, and then click Register. 6. Use SQL Server Enterprise Manager to view the contents of the UserS table. You will see a new row, the new user name is in this line with the generated password hash. 7. Return to the Logon web page, re-enter your password, and then click Logon. You will see the "Logon Successful: User IS Authenticated" message. 8. Please enter an invalid password now (the username remains unchanged). You will see the "Invalid UserName or Password" message. 9. Turn off Internet Explorer.
Back to top