Sunday, August 29, 2010

From Authentication

Forms Authentication is a mechanism to allow only authenticated user with valid credential to view a particular page or group of pages/folders and stop unauthenticated or anonymous user outside the secure boundary.

Forms authentication uses an authentication ticket that is created when a user logs on to a site, and then it tracks the user throughout the site. The forms authentication ticket is usually contained inside a cookie.

However, ASP.NET version 2.0 supports cookieless forms authentication, which results in the ticket being passed in a query string.

Forms authentication processing is handled by the FormsAuthenticationModule class, which is an HTTP module that participates in the regular ASP.NET page-processing cycle. This document explains how forms authentication works in ASP.NET 2.0.

There are two very important features of a Security System that we should formally define, one of which I've already mentioned a number of times in the article:

# Authentication answers the question "Who is the caller?"
# Authorization answers the question, "Does the caller have the right to access this Web method?"

Authentication - Authentication is the means by which you obtain the Identity of the User by validating their credentials against a known Authority, ie: Active Directory, Database Store, Microsoft Passport Account etc. If the credentials can't be validated then the Authentication process fails and the User will assume the Identity of IUSR_Anonymous. Remember that the Web is anonymous by nature, so the only way to determine who a particular visitor is to authenticate them by having them provide user credentials (a username/password, usually).

Authorization - Authorization occurs after Authentication and involves using information obtained during the Authentication process to determine whether to grant or deny access to a given resource based on that Users role in the Application. That is, if you are trying to access a Web page that only a particular user can access, the first step performed is to authenticate you - who is this guy making the request? - and then, based on that authentication, you must be authorized to view the particular data you are requesting.

ASP.NET 2.0 defines a set of HTTP modules in the machine-level Web.config file. These include a number of authentication modules as shown here:

<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule">
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule">
<add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule">

Only one authentication module is used for each request.The authentication module that is used depends on which authentication mode has been specified by the authentication element, usually in the Web.config file in the application's virtual directory.

The FormsAuthenticationModule class is activated when the following element is in the Web.config file.

<authentication mode="Forms">

Set the Web Config file for Form Authentication. You can define multiple config file in different directories for a single applcation.

By default it is set for window change it to Form.

<authentication mode="Forms">
<forms cookieless="UseDeviceProfile" defaulturl="default.aspx" enablecrossappredirects="false" loginurl="Login.aspx" name=".ASPXAUTH" path="/" protection="All" requiressl="false" slidingexpiration="true" timeout="30">


The default attribute values are described below:

* loginUrl is the name of the page where user will be redirected when they will try to enter into secure page/folders of the website.

* protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.

Possible values are :- All,Encription,None,Validation

*timeout* is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.

* name and path are set to the values defined in the application's configuration file.By default its value is .ASPXFORMSAUTH.

* requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.

* slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.
* defaultUrl is the name of the page where user will be redirected by default after they are logging in from home page or not secured page.
* cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.

Possible values for Cookieless

* UseCookies. This value forces the FormsAuthenticationModule class to use cookies for transmitting the authentication ticket.
* UseUri. This value directs the FormsAuthenticationModule class to rewrite the URL for transmitting the authentication ticket.
* UseDeviceProfile. This value directs the FormsAuthenticationModule class to look at the browser capabilities. If the browser supports cookies, then cookies are used; otherwise, the URL is rewritten.
* AutoDetect. This value directs the FormsAuthenticationModule class to detect whether the browser supports cookies through a dynamic detection mechanism. If the detection logic indicates that cookies are not supported, then the URL is rewritten.

* enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.


passwordFormat : Format the password will be stored in. Valid values include Clear, SHA1, and MD5. SHA1 and MD5 are both hashing algorithms that make storing passwords in the Web.config more secure.

User : This is the area to store the username and password. You can secure the passwords by running the HashPasswordForStoringInConfigFile function to get the hashed password. I will demonstrate this later.


Deny | Allow : This section allows us to deny or allow users to the site. ? = anonymous/unauthenticated users and * means all users. This section also allows us to specify certain users, and allow or deny permissions.

Create a Ticket
DataRow [] rows = dSet.Tables[0].Select( " UserName = '" + userName+ "' AND Password = '" + password + "'" );

// record validated

if (rows.Length > 0)


// get the role now

string roles = rows[0][ "Roles" ].ToString();

// Create forms authentication ticket

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (

1, // Ticket version

userName, // Username to be associated with this ticket

DateTime .Now, // Date/time ticket was issued

DateTime .Now.AddMinutes(50), // Date and time the cookie will expire

rememberUserName, // if user has chcked rememebr me then create persistent cookie

roles, // store the user data, in this case roles of the user

FormsAuthentication .FormsCookiePath); // Cookie path specified in the web.config file in tag if any.

// To give more security it is suggested to hash it

string hashCookies = FormsAuthentication .Encrypt(ticket);

HttpCookie cookie = new HttpCookie ( FormsAuthentication .FormsCookieName, hashCookies); // Hashed ticket

// Add the cookie to the response, user browser


// Get the requested page from the url

string returnUrl = Request.QueryString[ "ReturnUrl" ];

// check if it exists, if not then redirect to default page

if (returnUrl == null ) returnUrl = "~/Default.aspx" ;


No comments: