//
you're reading...
ASP.NET

Creating Credential Store for Form Authentication in ASP.NET 3.5

Form Authentication in ASP.NET: when we don’t want to validate user on window credential, in such cases we can take help of ASP.NET infrastructure for implementing our own authentication infrastructure which includes custom login page that validate user against credentials like database and later established security context on each request. ASP.NET leverages its framework to support handle for cookie and establishes the security context for each web request, this is called form authentication.

Points to remember:

1) Form authentication follows ticket system, which user gets at the time of login with other basic information attached to it. This is called authentication ticket. And this is done by cookie for assigning authentication tickets to client which is also called “cookie authentication”.

2) When request comes from anonymous user for a web page, ASP.NET checks for this ticket, when it don’t get, it redirect it to login page.

3) When ASP.NET detects the authentication ticket, and user is validated, then runtime automatically sets authentication cookie, which will contain authentication ticket and then redirect user to requested page. This is accomplishing by calling FormAuthentication class method.

Why to choose Form authentication:

1. You have full control over the authentication code.

2. You have full control over the appearance of the login form.

3. It works with any browser.

4. It allows you to decide how to store user information

How to implement Form Authentication:

Step 1: Configure forms authentication in the web.config file.

Below is default which visual studio set for us, change it to form authentication.

<authentication mode=”Windows” />

<!–

The <customErrors> section enables configuration

of what to do if/when an unhandled error occurs

during the execution of a request. Specifically,

it enables developers to configure html error pages

to be displayed in place of a error stack trace.

Change it to form;

<authentication mode=”Forms”>

we have lots of attribute for configuring form authentication like below;

For this example, we wil keep simple like below

<authentication mode=”Forms”>

<forms name=”MyCookieName” timeout=”20″ loginUrl=”dbLogin.aspx”>

<credentials passwordFormat=”SHA1″>

<user name=”vishal” password=”123″/>

<user name=”nayan” password=”321″/>

</credentials>

</forms>

</authentication>

Notice here that we are storing credential in web cofig file itself. We can store then anywhere we wish to, i.e. database

<credentials passwordFormat=”SHA1″>

<user name=”vishal” password=”123″/>

<user name=”nayan” password=”321″/>

</credentials>

Step 2: Next we have to deny anonymous user;

<authorization >

<deny users=”?”/>

</authorization>

The question mark (?) is a wildcard character that matches all anonymous users. By including

This rule in your web.config file, you specify that anonymous users are not allowed. They all should be authenticated.

Step 3: Now we have to create custom login page which takes user username and password credential and validate them against credential store which is web.config file.

HTML for this is as below;

<asp:Panel ID=”MainPanel” runat=”server” Width=”380px”

BorderColor=”Silver” BorderStyle=”Solid” BorderWidth=”1px”>

<table>

<tr>

<td width=”30%” style=”height: 43px”>

User Name:</td>

<td width=”30%” style=”height: 43px”>

<asp:TextBox ID=”UsernameText”  runat=”server” Width=”80%”>

</asp:TextBox>

<asp:RequiredFieldValidator  ID=”UsernameRequiredValidator”

ControlToValidate=”UsernameText” ErrorMessage=”*” runat=”server”>

</asp:RequiredFieldValidator>

<asp:RegularExpressionValidator ID=”UsernameValidator”

runat=”server” ControlToValidate=”UsernameText”

ValidationExpression=”[\w| ] *”

ErrorMessage=”Invalid Username”>

</asp:RegularExpressionValidator>

</td>

</tr>

<tr>

<td width=”30%” style=”height: 26px”>

Password:</td>

<td width=”30%” style=”height: 43px”>

<asp:TextBox id=”PasswordText” runat=”server” TextMode=Password

Width=”80%”></asp:TextBox>

<asp:RequiredFieldValidator id=”PwdRequiredValidator”

ErrorMessage=”*”  runat=”server”

ControlToValidate=”PasswordText”></asp:RequiredFieldValidator>

<asp:RegularExpressionValidator ID=”PwdValidator”

ControlToValidate=”PasswordText” runat=”server”

ErrorMessage=”Invalid Password”

ValidationExpression='[\w| !”§$%&amp;/()=\-?\*]*’>

</asp:RegularExpressionValidator>

</td>

</tr>

</table>

<br />

<asp:Button ID=”LoginAction” runat=”server”

Text=”Login” /><br />

<asp:Label ID=”LegendStatus” runat=”server”

EnableViewState=”false” Text=”” /></asp:Panel>

</asp:Panel>

You see here we have used Validation control each for username and password textbox;

Username: ValidationExpression=”[\w| ] *”

It may contain letters, digits, and spaces only. Therefore, the validation expression looks like this:

Password: ValidationExpression='[\w| !”§$%&amp;/()=\-?\*]*’>

To support special characters only

Step 4: Now we have to write code for validating user agains credential store, which in our case is web.config file.

There are multiple way to handle the login of user i.e. using web config credential , using data store credential , using persistence cookie for authentication and sometime without it, then creating your own credential store in web config.

So lets us try out each of them

A) Simple login using credential stored in web config and validating username and password  against it using Authenticate method.

protected void LoginAction_Click(object sender, EventArgs e)

{

Page.Validate();

if (!Page.IsValid)

{

return;

}

if (FormsAuthentication.Authenticate(UsernameText.Text, PasswordText.Text))

{

// Create the ticket, add the cookie to the response

// and redirect to the originally requested page

FormsAuthentication.RedirectFromLoginPage(UsernameText.Text, false);

}

else

{

// Username and password are not correct

LegendStatus.Text = “Invalid username or password!”;

}

}

Point to remember here:

1. We have used Page.Validate because is that validation controls by default use JavaScript for client-side validation. When calling Page.Validate (), the validation takes place on the server

2. FormsAuthentication.Authenticate do following jobs for us

1) Create authentication ticket

2) encrypt this authentication ticket information.

3) create a cookie to persist the encrypted information.

4) Add this cookie to HTTP response, sending it to client.

5) Redirect the user to requested page

B) How to create credential store in web.config file manually for user registration.

Step1 : Create a Interface which wil have two methods , one for creating user and other for authenticating user.

public interface ICredentialStore

{

bool Authenticate(string username, string password);

void CreateUser(string username, string password);

}

Step 2: Write another class which wil implement this interface and here we will write implementation for these two methods.

public class DefaultCredentialStore:ICredentialStore

{

#region ICredentialStore Members

public bool Authenticate(string username, string password)

{

return FormsAuthentication.Authenticate(username, password);

}

public void CreateUser(string username, string password)

{

Configuration MyConfig = WebConfigurationManager.OpenWebConfiguration(“~/”);

ConfigurationSectionGroup SystemWeb = MyConfig.SectionGroups[“system.web”];

AuthenticationSection AuthSec = (AuthenticationSection)SystemWeb.Sections[“authentication”];

AuthSec.Forms.Credentials.Users.Add(

new FormsAuthenticationUser(username,

FormsAuthentication.HashPasswordForStoringInConfigFile(username, “SHA1”)));

MyConfig.Save();

}

#endregion

}

Notice this line here;

AuthSec.Forms.Credentials.Users.Add(

new FormsAuthenticationUser(username,

FormsAuthentication.HashPasswordForStoringInConfigFile(username, “SHA1”)));

We are applying hashing algorithm to encryp the password, this is important because values

Step 3: Create a Register button and on Click of it write below code;

protected void RegisterAction_Click(object sender, EventArgs e)

{

Page.Validate();

if (Page.IsValid)

{

ICredentialStore cred = this.CreateStore();

cred.CreateUser(UsernameText.Text, PasswordText.Text);

LegendStatus.Text = “User created successfully, you can log in now!”;

}

else

{

}

}

Here we are creating Credential store manually at the runtime;

private ICredentialStore CreateStore()

{

string ConfigEntry = WebConfigurationManager.AppSettings[“CredentialStoreClass”];

string[] ConfigParts = ConfigEntry.Split(new char[] { ‘,’ });

Assembly CurrentAsm = Assembly.Load(ConfigParts[0].Trim());

ICredentialStore Store = (ICredentialStore)CurrentAsm.CreateInstance(ConfigParts[1].Trim());

if (Store == null)

throw new Exception(“Invalid credential store configuration!”);

else

return Store;

}

Step 4: Run the application and try to register.


Now check in web.config

<credentials passwordFormat=”Clear”>

<credentials passwordFormat=”SHA1″>

<user name=”bumpy” password=”9912C8866306C0B968BCF017AD29FCF3E50CBACA” />

</credentials>

Here you can see we have created username as bumpy with a password which is hashed now.

Step 5: Now we try to login with this newly created login detail. On the OnClick for login button write below code;

protected void LoginAction_Click(object sender, EventArgs e)

{

Page.Validate();

if (!Page.IsValid) return;

ICredentialStore cred = this.CreateStore();

if (cred.Authenticate(UsernameText.Text, PasswordText.Text))

{

FormsAuthentication.RedirectFromLoginPage(UsernameText.Text, false);

}

else

{

LegendStatus.Text = “Invalid username or password!”;

}

}

C. Relation Between Cookie and Form Authentication: In starting ,we discussed how user get authentication ticket  , which is actually a cookie.  So while configuring form authentication , we have option to configure the cookie behavior, when we don’t want the runtime to use cookie.

So we have four way to configure cookieless form authentication.

1) UseCookies: Using this setting actually make its compulsory to usecookies when working with forms authentication. This requires the client browser to support cookies. If the browser does not support cookies, forms authentication will simply not work with that setting activated. As it will never receive a valid authentication cookie from the browser, ASP.NET redirects back to the login page over and over again, and you end up in an endless loop of presented login pages.

2) UseURI: If this configuration option is selected, cookies will not be used for authentication.

Instead, the runtime encodes the forms authentication ticket into the request URL, and the infrastructure processes this specific portion of the URL for establishing the security context

3) AutoDetect: Results in the use of cookies if the client browser supports cookies. Otherwise,

URL encoding of the ticket will be used. This is established through a probing mechanism.

4) UseDeviceProfile: Results in the use of cookies or URL encoding based on a device profile configuration stored on the web server

D. What is persistence and non-persistence cookies in Form authentication.

Non-Persistence cookie : If user closes the browser the cookie is immediately removed. From security point of view this is important.

i.e. passing false for createPersistenceCookie.

Persistence cookie: If you are performing authentication for personalization rather than for controlling access to restricted resources, you may decide that the usability advantages of not requiring users to log in on every visit outweigh the increased danger of unauthorized use. In such scenario, persistence cookie is used.

Point to remember here:

1) Persistence cookie do not expire unless FormAuthentication.SignOut() is not called.

2) Persistence cookie are not affected by timeout value in <form> element in web.config.

3) If we want persistence cookie to expire, we have handle this manually.

So let us create an another login page which will have persistence cookie support and we will manually set time for signout.

protected void LoginAction_Click(object sender, EventArgs e)

{

Page.Validate();

if (!Page.IsValid) return;

if (FormsAuthentication.Authenticate(UsernameText.Text, PasswordText.Text))

{

HttpCookie AuthCookie;

AuthCookie = FormsAuthentication.GetAuthCookie(UsernameText.Text, true);

AuthCookie.Expires = DateTime.Now.AddMinutes(5);

Response.Cookies.Add(AuthCookie);

Response.Redirect(FormsAuthentication.GetRedirectUrl(UsernameText.Text, true));

}

else

{

// Username and password are not correct

LegendStatus.Text = “Invalid username or password!”;

}

}

Now , we will write code for default.aspx, page which user is requesting for. This page will have a signout button.

Open default.aspx and put a button for signout. Open default.aspx.cs and write below codes.

protected void SignOutAction_Click(object sender, EventArgs e)

{

FormsAuthentication.SignOut();

FormsAuthentication.RedirectToLoginPage();

}

For sake of more understanding , I have written few informative codes. These information are available irresepective of type of authentication we use.

And  when u click to signout , you will be redirected to login page.

Hope you enjoyed reading about this simple but interesting topic of form authentication.

Cheers

Advertisements

About Vishal

Vishal Nayan is a seasoned professional with hand on Experience on Mircrosoft Technologies. He always look for challenging IT position that allows him to learn new Microsoft Technologies while utilizing experience of Project Development and Software Engineering Ethics. A MCP in WCF ,and looking forward for more.

Discussion

6 thoughts on “Creating Credential Store for Form Authentication in ASP.NET 3.5

  1. What is “MyCookieName” neans in the following code? Is it Login page’s form id?
    ———————————————————————————-

    —————————————————————————————–

    Posted by Deepu Balakrishnan | 2011/10/28, 2:13 PM
  2. I am really grateful to the owner of this web site who has shared this enormous article at here.

    Posted by Isaac | 2013/02/18, 1:01 PM
  3. This is a good tip especially to those fresh to the blogosphere.
    Brief but very precise info… Thank you for sharing this one.
    A must read post!

    Posted by tropicana casino | 2013/04/09, 4:50 PM
  4. Your are beautiful web marketer. The site launching stride will be unbelievable. This variety of feels that you will be executing just about any unique key. Furthermore, The contents are usually must-see. you have carried out an outstanding activity during this subject!

    Posted by golf swing | 2013/06/22, 4:32 PM

Trackbacks/Pingbacks

  1. Pingback: DotNetShoutout - 2011/04/06

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow Vishalnayan on WordPress.com

Blog Stats

  • 210,065 hits
%d bloggers like this: