Wednesday, June 27, 2007

Security Features in ASP.NET - Authentication


Introduction

Security is one of the primary concerns for both developers and application architects. As there are lots of different types of website with varying security needs, the developers need to know how the security works and choose the appropriate security model for different applications. Some websites collect no information from the users and publish the information that is available widely such as search engine. Meanwhile, there are other sites that may need to collect sensitive information from their users (e.g. credit card numbers and other personal information). These websites need much stronger security implementation to avoid malicious attacks from external entities.

Difference of ASP and ASP.NET Security Flow

The security flow for ASP.NET page request is different from the classic ASP security flow. In ASP, IIS impersonates the authenticated user by default, and in ASP.NET, the developer has more control over configuring security at different level [2].

ASP.NET Security Fundamental Operations

Security in the context of ASP.NET application involves 3 fundamental operations [1,4,5]:

  • Authentication: the process of validating the identity of a user to allow or deny a request [4,9,10]. This involves accepting credentials (e.g. username and password) from the users and validating it against a designated authority. After the identity is verified and validated, the user is considered to be legal and the resource request is fulfilled. Future request from the same user ideally are not subject to the authentication process until the user logs out of the web application.

  • Authorization: the process of ensuring that users with valid identity are allowed to access specific resources.

  • Impersonation: this process enables an application to ensure the identity of the user, and in turn make request to the other resources. Access to resources will be granted or denied based on the identity that is being impersonated. In other words, impersonation enables a server process to run using the security credentials of the client [6,9]. Thus, the ASP.NET applications are capable to execute the identity of client on whose behalf they are operating.

Since there are a lot of ASP.NET security features to cover, this paper will only focus on authentication in ASP.NET.

Authentication in ASP.NET

Authentication is one of the foremost features of web application's security. In ASP.NET, authentication is done at two levels [2]. First, IIS* will perform the required authentication then send out the request to ASP.NET, as described in Figure 1. For ASP.NET application, the underlying web server is IIS. Therefore, every ASP.NET application can continue to leverage the security options provided by IIS.

Figure 1 - Security Flow of IIS and ASP.NET
Source: MSDN Library
Figure 1 - Security Flow of IIS and ASP.NET

When the user requests a specific resource on the system, that request will come to IIS. IIS authenticates the user requesting the resource and then hands off the request and the security token for the authenticating user to ASP.NET worker process. ASP.NET worker process will decide whether to impersonate the authenticated user supplied by IIS or not.

If impersonation is enabled in the configuration setting in Web.config file, then ASP.NET worker process impersonates the authenticated user. Otherwise, the thread will run under the ASP.NET worker process identity. After all, ASP.NET checks whether the authenticated user is authorized to access these resources. If they are allowed to, ASP.NET serves the request; otherwise it sends an "access-denied" error message back to the user.

ASP.NET provides built-in support for user authentication through several authentication providers [1,4]:

  • Forms-based authentication: the application is secured by using a custom authentication model with cookie support.

  • Passport authentication: the application is secured by using Microsoft® Passport authentication. Passport is a single sign-on technology developed by Microsoft for use on the web.

  • Windows authentication: the application is secured by using integrated windows authentication where access to a web application is allowed only to those users who are able to verify their windows credentials.

There are scenarios where some applications do not use the authentication at all or the developer may want to develop custom authentication code. In this case, ASP.NET can set the authentication mode to None. However, the topic is out of scope of this article since it will only cover the Forms-based, passport and windows authentications.

Forms-Based Authentication

Forms-based authentication is used to implement customized logic for authenticating users without having to worry about session management using cookie. It gives developer more access to specify which files on the site can be accessed and by whom, and allows identification of a login page [3,7].

This mechanism will automatically redirect the unauthenticated user to login page and ask them to provide proper credentials (e.g. username/password combination). If login is successful, ASP.NET then issues the cookie to the user and redirect them to specific resources that they originally requested. This cookie allows the user to revisit particular protected resources without having to repeatedly log in. The mechanism is shown as below:

Figure 2 - Form Authentication Flow
Figure 2 - Form Authentication Flow

In figure above, the user requests the restricted resources first. This request will go to IIS first and the user is authenticated by IIS. If the anonymous access is enabled in IIS or the user is successfully authenticated, it will hand off the request to ASP.NET application. ASP.NET checks to see whether a valid authentication cookie is attached to the request. If it is, it means the user credentials has been previously authenticated. ASP.NET will then perform the authorization check. If the user is authorized to access those resources, the access will be granted. Otherwise, the "access-denied" message is sent.

If the request does not have any cookie attached, ASP.NET redirects the user to the login page and solicits the credentials then resubmits for authentication. The application code checks those credentials. If authenticated, ASP.NET will attach the authentication ticket in the form of cookie to the response. If failed, the user can be redirected back to the login page telling the user that the username/password is invalid.

Set Up Forms-Based Authentication

Generally, setting up the Forms-based authentication involves 4 steps [2]:

1. Enable anonymous access in IIS

This has to be done as most of the users are considered to be non-Windows users, so they can get through IIS to get to ASP.NET. ASP.NET will always allow anonymous access to the login page though.

2. Configure <authentication> section in Web.config file

Web.config file contains the information related to the level and type of authentication service that is provided for a web application. The Forms-based authentication is enabled for a web application by setting the authentication mode attribute to Forms [3,8]:

<authentication mode="Forms">
<forms name="Login"
loginURL="Login.aspx"
protection="All"
timeout="10"
path="/" />
</authentication>

As shown by the code above, the name attribute is the name of HTTP cookie. The attribute loginURL is set to Login.aspx, which is the web page that is used for authenticating user credentials. The requests are redirected to particular URL in loginURL if the user is not authenticated.


The cookie protection is set to All. This causes the ASP.NET runtime to not only encrypt the cookie contents, but also validate the cookie contents. The valid values for protection attribute are All, None, Encryption, and Validation [9,10]. If the value is specified to None, it does not use either encryption or validation. Specifying Encryption will encrypt the cookie using triple DES or DES encryption algorithm; the data validation is not done on the cookie. The Validation specifies to validate that the cookie data has not been altered in the transit, instead of encrypting the contents of the cookie.


The timeout is set to 10, which means in 10 minutes the authentication cookie will expire. The idea behind this is to reduce the chance someone stealing the form authentication cookie. By reducing this, the cookie will be regenerated more often.


The path attribute refers to the path of cookie to be sent to the client. It is set to "/" which means the cookie path is the root directory.


The actual authentication (i.e. prompting the user to provide credentials) is performed by Login.aspx. The following code in Login.aspx passes the username and password that the user entered to the static System.Web.Security.FormsAuthentication method called Authenticate:





If(FormsAuthentication.Authenticate(Username.Text, Password.Text))
{
FormsAuthentication.RedirectFromLoginPage(Username.Text, false);
}

The code above will first check the username and password passed by the user, if they are valid, it will return true then go to the next statement. Next, it creates an authentication cookie, attaches it to the outgoing response and redirects user to original requested page. The second parameter specifies whether the authentication should be session cookie (false) or a persistent cookie (true) [7].

3. Configure <authorization> section in Web.config file

Add authorization support to section of ASP.NET web application. To do so, add the <authorization> section in Web.config file:





<configuration>
<system.web>
<authorization>
<allow users="Cynthia" />
<deny users="*" />
</authorization>
</system.web>
</configuration>

As explained above, after the user provides the valid credentials, the user is redirected to the specific protected page. However, The authorization section in this code will deny access to all users, but exclusively allow access to Cynthia.


In some cases, the following code is used to allow any authenticated user to access the protected resources [2]:





<authorization>
<deny users="?" />
<allow users="*" />
</authorization>

The "?" means all unauthenticated, anonymous user [5]. It will deny all unauthenticated or anonymous users.


One important thing to note that the code:





<deny users="*" />
<allow users="Cynthia" />

is different from:





<allow users="Cynthia" />
<deny users="*" />

since ASP.NET will stop at <deny users="*" /> and abandon the rest statements appear after that [7]. Therefore in the first one, it will deny ALL users instead of giving access to Cynthia only.

4. Create Login Page

This is the last step for redirecting unauthenticated users, so they can provider their credentials, usually in a form of username and password and log on to protected resources. The login page must validate the submitted credentials against a database of some custom method. Valid usernames and passwords can be stored in the Web.config file in credentials section:





<credentials passwordFormat="Clear">
<user name="Cynthia" password="cyn">
<user name="Flora" password="flo">
<user name="Fenty" password="fang">
</credentials>

However, storing password in clear text is unreasonable for security. Moreover, it is unrealistic to store thousands of names and passwords in Web.config file [2,7]. To address this problem, the usernames and passwords are stored in the database. This approach makes the Web.config file no longer have the <credentials> section. There will be also some changes in Login.aspx since the credentials will be tested to match against result query from database that stores the usernames and passwords.


In Login.aspx, instead of using FormsAuthentication.Authenticate to validate user credentials, it will call a local method (i.e. CheckValidity) which makes use a SQL query to determine whether the credentials are valid. The sample code as follows:





Bool CheckValidity(String username, String password)
{
SqlConnection conn = new SqlConnection ("server=localhost;
database=weblogin; uid=sa; pwd=");
try
{
conn.Open();
String sqlQuery = "select count (*) from users
where username =\' " + username +
"\' and password=\' " + password + "\' ";
SqlCommand command = new SqlCommand(sqlQuery, conn);
int count = (int)command.ExecuteScalar();
return (count>0);
}

catch (SqlException e)
{
return false;
}
finally
{
conn.Close();
}
}

This function will check for username and password given by the user to match against the database (i.e. users table) and it will return 0 if the credentials are not valid because there is no such record in the database, otherwise it will return 1, which means the credentials are valid.


Benefit of Forms-Based Authentication


There are some benefits of using Forms-based authentication [5]:



  • Developer can configure Forms-based authentication for various parts of the website differently because the Web.config is a hierarchical XML document.

  • Administrator and developer can change the authentication scheme quickly and easily in the Web.config file

  • Administration is centralized because all the authentication entries are in one place - Web.config file.

Passport Authentication


As stated above, this authentication mechanism provides a centralized authentication service that offers single sign-in for access the member sites. The following scenarios support the use of Passport Authentication [2]:



  • The username and password database or login page is not maintained; and

  • Willing to provide personalized content; and

  • The site will be used in conjunction with other Passport sites; and

  • Willing to give single sign-in capability to the users

Set Up Passport Authentication


To implement this authentication mode, Passport SDK (Software Development Kit) has to be installed on the server and register with Microsoft® Passport [1,2]. The following code is specified in the Web.config file where the authentication mode is set to Passport:





<authentication mode="Passport">
<passport redirectURL="internal" />
</authentication>

The redirectURL attribute of Passport section is set to internal, which means the unauthenticated request will receive common error message. The value of redirectURL may contain a string other than internal, which is considered to be a URL, which the unauthenticated request will be sent to.


Windows Authentication


This type of authentication is possibly the easiest of all to implement. Windows authentication can be used in conjunction with almost all authentication methods provided by IIS (e.g. Basic, Digest, NTLM or Kerberos Authentication), except Anonymous Authentication [2,4]. There is no need to write any code to validate the user as IIS has already authenticated their Windows credentials. Basically, Windows authentication makes use of the authentication capabilities of IIS. IIS will complete its authentication first then ASP.NET will use the authenticated identity's token to decide whether the access is granted or denied.


This mechanism is usually implemented when the users are part of Windows domain and the authenticated users are to be impersonated so that the code is executed in the same security context of the user's Windows account [4].


When a user requests specific resources, this request will go to IIS. IIS authenticates the user and attaches the security token to it. It will then pass the authenticated request and security token to ASP.NET. If impersonation is enabled, ASP.NET impersonates the user using the security token attached and sees whether the user is authorized to access the resources in the <authorization> section in Web.config file. If the access is granted, ASP.NET will send the requested resources through IIS, or else, it sends error message to the user.



Set Up Windows Authentication


The only step in implementing the Windows Authentication is to set the authentication mode to Windows and deny access to anonymous user in Web.config file as shown below:





<authentication mode="Windows">
...
</authentication>


<authorization>
<deny users="?" />
</authorization>

The impersonation is enabled only if the code is to be under same security context as that of the user account. Again, this is done in the configuration file.


Conclusion


Authentication in ASP.NET is one of the best features of the web application's security, which it is divided into 3 different built-in providers: Forms-based, Passport and Windows Authentication. The Forms-based and passport authentication do not require the users to be as Windows users. Meanwhile, the windows authentication is designed for users that are part of Windows domain. Forms-based authentication provides the unauthenticated users with the login page to ask them for their credentials, and it will validate those credentials against the designated authority. Once authenticated, the valid users will be granted to access the original requested resources. Future request from those users of the protected resources will automatically be redirected without having to repeatedly log in. On the other hand, if the users are not authorized to access specific resources, it will send the access-denied message back to the users. For Passport authentication, just simply install the Passport SDK on the server and register with Microsoftâ Passport. This mechanism offers a single sign-in provided by Microsoft to allow access to the member sites. Whereas, the Windows authentication is the easiest to implement as it does not require writing any code for authentication. It works in conjunction with IIS authentication mechanisms such as Basic, Digest, NTLM or Kerberos. However, it does not support for IIS Anonymous authentication.





* IIS (Internet Information Server): Microsoft's web server that hosts the web application. It has built-in support for authenticating clients (i.e. Anonymous, Basic, Digest and Integrated/NTLM/Kerberos Authentication) who request the web content stored in IIS site [5].

0 Comments: