Welcome to the amazing dot net programming

Author: Vijaya Kumar
Contact:

    

  

Get updates by e-mail

HP Computer Museum

 

 

 

 

free website submission search engine seo optimization

 

Powered by Blogger

November 13, 2006

Using Forms Authentication with SQL Server in ASP.NET 1.1

Most of the Web applications we have to provide the authentication to check the use credentials to logon to the secured pages in the site. By default IIS provides the windows authentication which doesn't need to write any single line of code instead of some settings in IIS. We can use Forms authentication in ASP.NET to verify the user credentials in order to access the secured pages. But for Forms authentication, we have to write little bit of code, below i have added the setps to setup the forms
authentication.

Step 1. Create a Web Application with a Logon Page
Step 2. Configure the Web Application for Forms Authentication
Step 3. Develop Functions to Generate a Hash and Salt value
Step 4. Create a User Account Database
Step 5. Use ADO.NET to Store Account Details in the Database
Step 6. Authenticate User Credentials against the Database
Step 7. Test the ApplicationAdditional Resources

Web applications that use Forms authentication often store user credentials (user names and passwords) together with associated role or group lists in MicrosoftSQL Server.

This How To describes how to securely look up user names and validate passwords against SQL Server. There are two key concepts for storing user credentials securely:

Storing password digests. For security reasons, passwords should not be stored in clear text or encrypted format in the database. This How To describes how to create and store a one-way hash of a user's password rather than the password itself. This approach is preferred to storing a clear text or encrypted version of the user's password, for two reasons. First, it helps to prevent an attacker who gains access to our user store from obtaining the user passwords. In addition, this approach helps you to avoid the key-management issues associated with encryption techniques.

Using a salt value when creating the hash helps to slow an attacker who is attempting to perform a dictionary attack (where an attacker attempts to decipher the key used for hashing). This approach gives you additional time to detect and react to the compromise.
Important: The one drawback of not storing passwords in the database is that if a user forgets a password, it cannot be recovered. As a result, your application should use password hints and store them alongside the password digest within the database.

Validating user input. Where user input is passed to SQL commands, for example as string literals in comparison or pattern matching statements, great care should be taken to validate the input, to ensure that the resulting commands do not contain syntax errors and also to ensure that a hacker cannot cause your application to run arbitrary SQL commands. Validating the supplied user name during a logon process is particularly vital as your application's security model is entirely dependent on being able to correctly and securely authenticate users.

Step 1. Create a Web Application with a Logon Page

Start Visual Studio .NET and create a new C# ASP.NET Web application called FormsAuthSQL.

Use Solution Explorer to rename WebForm1.aspx to Logon.aspx

Add the controls to Logon.aspx to create a simple logon form.

Your Web page should resemble the one illustrated in Figure 1.


Figure 1. Logon page Web form

Step 2. Configure the Web Application for Forms Authentication

Use Solution Explorer to open Web.config.

Locate the <authentication> element and change the mode attribute to Forms. Add the following <forms> element as a child of the <authentication> element and set the loginUrl, name, timeout, and path attributes as follows.


<authentication mode="Forms">

<forms loginUrl="logon.aspx" name="sqlAuthCookie" timeout="60" path="/">

</forms>

</authentication>


Add the following <authorization> element beneath the <authentication> element. This will allow only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the logon.aspx page.


<authorization>

<deny users="?" />

<allow users="*" />

</authorization>

Step 3. Develop Functions to Generate a Hash and Salt value

This procedure adds two utility methods to your Web application; one to generate a random salt value, and one to create a hash based on a supplied password and salt value.

To develop functions to generate a hash and salt value

Open Logon.aspx.cs and add the following using statements to the top of the file beneath the existing using statements.

using System.Security.Cryptography;
using System.Web.Security;

Add the following static method to the WebForm1 class to generate a random salt value and return it 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 representation of the random number
return Convert.ToBase64String(buff);
}

Add the following static method to generate a hash value based on a supplied password and salt value.

private static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile( saltAndPwd, "SHA1");
hashedPwd = String.Concat(hashedPwd, salt);
return hashedPwd;
}

Step 4. Create a User Account Database

Run the the table Users script in SQL query analyzer to create the table.

CREATE TABLE [Users] (
[UserName] [varchar] (20) NOT NULL ,
[PasswordHash] [varchar] (40) NOT NULL ,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[UserName]
) ON [PRIMARY]
) ON [PRIMARY]

-- create stored procedure to register user details

CREATE PROCEDURE RegisterUser
@userName varchar(20),
@passwordHash varchar(40)
AS
INSERT INTO Users VALUES(@userName, @passwordHash)
GO

-- create stored procedure to retrieve user details
CREATE PROCEDURE LookupUser
@userName varchar(20)
AS

SELECT PasswordHash FROM UsersWHERE UserName = @userName
GO

Step 5. Use ADO.NET to Store Account Details in the Database

This procedure modifies the Web application code to store the supplied user name, generated password hash and salt value in the database.

To use ADO.NET to store account details in the database

Return to Visual Studio .NET and double-click the Register button on the Web form to create a button click event handler. Add the following code to the method.

int saltSize = 5;
string salt = CreateSalt(saltSize);
string passwordHash = CreatePasswordHash(txtPassword.Text,salt);

try
{
StoreAccountDetails(
txtUserName.Text, passwordHash);
}
catch(Exception ex)
{
lblMessage.Text = ex.Message;
}

Add the following using statement at the top of the file, beneath the existing using statements.

using System.Data.SqlClient;

Add the StoreAccountDetails utility method using the following code. This code uses ADO.NET to connect to the UserAccounts database and stores the supplied username, password hash and salt value in the Users table.

private void StoreAccountDetails( string userName, string passwordHash )
{
// 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;
//Usage of Sql parameters also helps avoid SQL Injection attacks. sqlParam = cmd.Parameters.Add("@userName", SqlDbType.VarChar, 20);
sqlParam.Value = userName;
sqlParam = cmd.Parameters.Add("@passwordHash ", SqlDbType.VarChar, 40);
sqlParam.Value = passwordHash;

try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch( Exception ex )
{
// Code to check for primary key violation (duplicate account name)
// or other database errors omitted for clarity
throw new Exception("Exception adding account. " + ex.Message);
}
finally
{
conn.Close();
}
}

Step 6. Authenticate User Credentials Against the Database

This procedure develops ADO.NET code to look up the supplied user name in the database and validate the supplied password, by matching password hashes.

To authenticate user credentials against the database

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
// 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;
//Usage of Sql parameters also helps avoid SQL Injection attacks. SqlParameter sqlParam = cmd.Parameters.Add("@userName", SqlDbType.VarChar, 20);
sqlParam.Value = suppliedUserName;

try
{
conn.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);
int saltSize = 5;
string salt = dbPasswordHash.Substring(dbPasswordHash.Length - saltSize);
reader.Close();
// Now take the password supplied by the user
// and generate the hash.
string hashedPasswordAndSalt = CreatePasswordHash(suppliedPassword, salt);
// Now verify them.
passwordMatch = hashedPasswordAndSalt.Equals(dbPasswordHash);
}
catch (Exception ex)
{
throw new Exception("Execption verifying password. " + ex.Message);
}
finally
{
conn.Close();
}
return passwordMatch;
}

Step 7. Test the Application

This procedure tests the application. You will register a user, which results in the user name, password hash and salt value being added to the Users table in the UserAccounts database. You will then log on the same user to ensure the correct operation of the password verification routines.

To test the application

Return to the Logon form and double-click the Logon button to create a button click event handler.

Add the following code to the Logon button click event handler to call the VerifyPassword method and display a message based on whether or not the supplied user name 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 authenticated
// At this point, an authentication ticket is normally created
// This can subsequently 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";
}

On the Build menu, click Build Solution.

In Solution Explorer, right-click logon.aspx, and then click View in Browser.

Enter a user name and password, and then click Register.

Use SQL Server Enterprise Manager to view the contents of the Users table. You should see a new row for the new user name together with a generated password hash.

Return to the Logon Web page, re-enter the password, and then click Logon. You should see the message "Logon successful: User is authenticated."

Now enter an invalid password (leaving the user name the same). You should see the message "Invalid username or password."

8 Comments:

At 2/24/2007 06:50:00 AM, Anonymous Anonymous said...

galveston royal carribean cruises

 
At 2/27/2007 01:20:00 AM, Anonymous Anonymous said...

I gathered a couple of pillows and put them under my head and chest and raised my butt up.
It didn't take us long to get into position and he was soon sliding himself into me very slowly.
He was right, his ukraine top child was touching some places it missed when we did it with him lying on top of me.
When he had himself buried he began long slow thrusts while pulling me back to him with a hand on each of my hips.
A few minutes of that and he let one hand go and reached around and gently massaged a nipple.
Between his young model driving deep inside of me and his fingers on my breast I knew I was going to explode quickly. "Don, I'm going to preteen model
"Honey, see if you can hold back a bit and maybe we can puss pedo at the same time.""I'll try."
I felt him stroking the shaft of his lolita while the head was in me and moving it in and out of me ever so slowly.
I could see what he was doing.
He was getting himself aroused with jacking himself off with only part of his preteen bbs in me so he could try and free teen porn at the same time as I would.
I could feel the heat rising in me and I threw my ass back at him and drove his preteen sample video all the way in as I felt my orgasm come over me. "Don I'm coming."

 
At 3/01/2007 06:32:00 AM, Anonymous Anonymous said...

teen
pictures
magic
lolits porno
Free Lolita Pix
lolita bbs video
best lolita bbs
zeps lolita bbs
xxx lolita pics
sun lolita pics
pedo lolita pics
underage lolita sex pics
tgp lolita sex
prelolita sex
lolita sex pictures
wow lolita tgp
russian lolita tgp links
lolita tgp site
lolita tgp free
best lolita tgp
art lolita tgp

 
At 3/05/2007 12:55:00 AM, Anonymous Anonymous said...

flights Djibouti

 
At 3/11/2007 09:38:00 PM, Anonymous Anonymous said...

I knew my mom was hot from the time I hit puberty. As soon as I began masturbating I was fantasizing about her. And later, in high school all the guys were always over to use my pool in the summer, hoping she would be home from work or be tanning on the weekends. Mom rarely disappointed too, sunning herself in a modest two-piece on the weekends while all my male friends gawked at her. If she ever knew she was the neighborhood hot mom she never gave any indication.
The older I got the more I thought about mom and every girl I dated was compared to her. I had a steady girlfriend through high school, but a careful eye would have seen that she was just a younger version of my mom and when I was with my girlfriend I often imagined she was my Mom. Not that she needed a younger version of herself. Mom was twenty-two when she had me, so when I was in high school she was in her thirties and looked like she could have been in her twenties. Mom had been a beauty queen in high school and the years hadnÒt diminished her looks one bit. Her long, sunny blond hair still fell past her shoulders, I used to play with it all the time when I was little, and her eyes still sparkled blue. And Mom has kept her amazing body. Seeing old pictures I think it got better after she had two kids. Her ass is rounder and plumper than when she was a teen and her breasts look heavier, theyÒre 36CÒs, I know from checking out her bras in the laundry, too. Sometimes thinking about Mom just makes my cock ach
e.
So anyway, IÒm twenty-two now, the same age that Mom was when she had me and sheÒs been my lover for over two years now. I found a way to make my fantasies come true when I was nineteen and away at college. They say that the meeting of all those different cultures and ideas is good. I know it was for me. Some of you may think what I did to get my Mom was wrong, but I canÒt say I have any regrets. HereÒs my story.
My freshman year at college I met this exchange student from India named free erotic sex stories. Saji was a great guy and we decided that we would be roommates during our sophomore year. When we became roommates we became the best of friends and I took him back home for a weekend. He stayed in the guest room and we had a great time. And I could tell by the way he looked at my Mom that free french very young 16 yrs old wanted her just as much as all my friends always had. But Saji was different. He actually said something. We were drinking in the dorm one night.
Dude, would you get pissed if I told you something? free galleri teen porn asked, taking a swig of his beer.
I donÒt think so. Try me. I replied.
Well, I have not been able to stop thinking about your mother. She is such a hottie.
I didnÒt know what to say, so I agreed.
She came to check on me the first night, she was standing in the doorway and I could see right through her nightgown. I felt really bad about thinking of your mother that way, but I couldnÒt help it.
I knew just the nightgown he was talking about. It always drove me crazy too. I tried to make him feel better, and maybe me too a little. If you think you feel bad, think how I feel. IÒm her son!
What? You think your mother is hot too? free gay anal was very surprised.
I had told him a little so I didnÒt see what there was to loose by telling him the rest. Dude, IÒve been fantasizing about my mom since I was a kid. How could I not? SheÒs like a goddess. free gay sex nodded his agreement. Sometimes I think I am doomed to never be completely happy with another girl.
So would you? You knowÅ I thought I knew what he meant, but didnÒt say anything. If you could, Saji continued, would you be with her?
IÅIÅuh, hell, of course I would. As weird as thatÒs supposed to be, I would in a heartbeat. Just thinking about it got me hard. But dude, there is no way she would ever even think about it. She loves my dad way too much. That part was true. My parents acted like they were as in love as the day they met. My dad worked hard and that meant being on business trips a few days every month, going to some regional office or another and every time he came back I would be able to hear my parents making love from down the hallway. My mother was so loud every time she came. Believe me, that had provided more fodder for fantasy than a hundred pornos could. And anyway, she would probably hate me, think I am some disgusting little freak if she knew how I feel.
There was a glint in SajiÒs eyes now. What if I could do something to help you? If I could make your fantasy come true, would you do it then?
I had no idea what he was talking about. It was all academic, so I said, Sure.
Then this is your lucky day, friend. free incest hentai went on to tell me how back in India his family was well-regarded herbalists and medicine men and that when his father came to this country he brought much of his knowledge with him. Saji had been studying with his father for as far back as he could remember his father had been mixing up elixirs that healed the family far faster than western medicine had to offer. But what Saji had to help me was not a medicine, he said. It was something his father would not teach him and Saji had only been able to learn by sneaking into his fatherÒs journals. What was it? Now that Saji had teased me I had to know what he was talking about. There was a mixture of powdered herbs that when combined acted like a psychotropic agent. What the hell was that, I asked him. Saji smiled and simply said, Mind control.
YouÒre out of your mind. What, am I going to hypnotize my mother into sleeping with me? I snorted.
No, itÒs nothing as clumsy as you would see in a movie, Saji told me. This, he said, worked over time. Several weeks to a month, depending on how strong-willed the subject was. Well, I knew Mom was pretty strong-willed. The subject did not turn into a zombie and best of all they had no idea what was happening. As far as the subject was concerned all of their thoughts and feelings were coming from them.
So why are you offering me this ancient family secret? I asked. There had to be a catch.
Because youÒre the only person here whoÒs truly been a friend to me. And, obviously I expect you to tell me every detail.
I donÒt know why I made the show of struggling over my decision, but I did. After a few minutes of silence I told Saji, Okay, what do I have to do?
When Saji went home for Spring Break he mixed up some of the herbs. Of course he wouldnÒt tell me what was in the mixture he brought back, but he assured me that it wouldnÒt do anything to hurt my mother. He handed me a big ziplock baggie of something that looked like green tea, but ground up more finely, and some written instructions, along with a vial of an amber oil. Saji said it had a very slight, bitter taste, but depending on what I slipped it into she would never notice. The oil was the activator. It was to be used after the herbs had softened Mom up. Lucky for me Mom has a cup of tea every evening after dinner, Saji said that should work perfectly because it would probably start kicking in when she was ready for bed.

 
At 3/04/2010 11:01:00 PM, Anonymous Anonymous said...

Remove everything, that a theme does not concern.

 
At 3/12/2010 09:39:00 PM, Anonymous Anonymous said...

And still variants?

 
At 12/29/2012 09:31:00 PM, Anonymous Anonymous said...

[url=http://ebiteua.com/forum54-prostitutki-khmelnitskogo-i-oblasti.html]Prostitutki KHmel`nitckogo[/url]

 

Post a Comment

<< Home

Google
 
Web dotnetlibrary.blogspot.com