Wednesday 10 August 2011

Security : ASP.NET 2.0


What's New in 2.0

This section describes the most important changes in ASP.NET 2.0 that you should be aware of when you perform a security code review. The main changes include:
  • Details in configuration files, such as connection strings, can be encrypted by using the Aspnet_regiis tool.
  • There are new membership APIs.
  • There are new role APIs.
Use the following questions to make sure that the code uses the new ASP.NET 2.0 features properly:
  • Does the code ensure that the connection strings configuration section is encrypted?
  • Does the code ensure that membership providers use strong passwords?
  • Does the code ensure that the roles cookie is encrypted and checked for integrity?
  • Does the code ensure that the roles cookie has a limited life time?
  • Does the code persist role manager cookies

Does the code ensure that the connection strings configuration section is encrypted?

When the code specifies the connection string in the connectionStrings configuration section, make sure that the connection strings configuration section is encrypted with the Aspnet_regiis.exe utility.
Because the connection string contains sensitive data, leaving it in plain-text format in configuration files makes your application vulnerable. For more information on encrypting the configuration section, see "How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI" at http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000005.asp and "How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA" at http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000006.asp.

Does the code ensure that membership providers use strong passwords?

The code should ensure that the membership provider uses a strong password policy by setting minRequiredPasswordLength, minRequiredNonAlphaNumericCharacters, and passwordStrengthRegularExpression attributes.
Because using weak passwords makes your application vulnerable to brute force and dictionary attacks, it is important to ensure that your Membership feature uses strong passwords.
The application should not contain code similar to the following example.
<membership>
  <providers>
    <add minRequiredPasswordLength="1" .../>
  </providers>
</membership>
  
Instead, the application should contain code similar to the following.
<membership>
  <providers>
    <add minRequiredPasswordLength="7", 
         minRequiredNonAlphanumericCharacters="1", 
         passwordStrengthRegularExpression ="" ... />
  </providers>
</membership>
  
Note   By default, the password strength policy for SqlMembershipProvider and ActiveDirectoryMembershipProvider has a minimum length of 7 characters and 1 non-alphanumeric character.

Does the code ensure that the roles cookie is encrypted and checked for integrity?

Make sure that the roles cookie is encrypted and checked for integrity. The cookieProtection attribute should be set to "All", which is the default case.
Cookies that are not encrypted and tamperproof make your application vulnerable to privilege escalation attacks through unauthorized modification of the role data.
The application should not contain code similar to the following example.
<system.web>
  <roleManager cookieProtection="None" ... />
</system.web>
  
Instead, the application should contain code similar to the following.
<system.web>
  <roleManager cookieProtection="All" ... />
</system.web>
  

Does the code ensure that the roles cookie has a limited life time?

A shorter life time limits the time when an attacker can use a stolen cookie to access the application.
The application should not contain code similar to the following example.
<system.web>
  <roleManager cookieTimeout="100" ... />
</system.web>
  
Instead, the application should contain code similar to the following.
<system.web>
  <roleManager cookieTimeout="10" ... />
</system.web>
  

Does the code persist role manager cookies?

Make sure that the roles cookie is not stored on the client by setting the createPersistentCookie attribute to false.
The code should not persist role manager cookies because they are stored in the user's profile and can be stolen if an attacker gains physical access to the user's computer. Role manager cookies can reveal sensitive information about your application's role structure that an attacker can exploit.
The application should not contain code similar to the following example.
<system.web>
  <roleManager createPersistentCookie="true" ... />
</system.web>
  
Instead, the application should contain code similar to the following.
<system.web>
  <roleManager createPersistentCookie="false" ... />
</system.web>

SQL Injection

Your code is vulnerable to SQL injection attacks wherever it uses input parameters to construct SQL statements. A SQL injection attack occurs when untrusted input can modify the logic of a SQL query in unexpected ways. As you review the code, make sure that any input that is used in a SQL query is validated or that the SQL queries are parameterized. Table 1 summarizes the SQL injection vulnerability and its implications. The following questions can help you to identify vulnerable areas:
  • Is the application susceptible to SQL injection?
  • Does the code use parameterized stored procedures?
  • Does the code use parameters in SQL statements?
  • Does the code attempt to filter input?

Is the application susceptible to SQL injection?

Pay close attention to your data access code. Scan for the strings "SqlCommand", "OleDbCommand", or "OdbcCommand" to help identify data access code. Identify any input field that you use to form a SQL database query. Check that these fields are suitably validated for type, format, length, and range.

Does the code use parameterized stored procedures?

Check that your code uses parameterized stored procedures and typed parameter objects such as SqlParameter, OleDbParameter, or OdbcParameter. Stored procedures alone cannot prevent SQL injection attacks. The following example shows the use of a SqlParameter.
SqlDataAdapter myCommand = new SqlDataAdapter("spLogin", conn);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parm = myCommand.SelectCommand.Parameters.Add(
                                "@userName", SqlDbType.VarChar,12);
parm.Value=txtUid.Text;
  
The typed SQL parameter checks the type and length of the input, and it ensures that the userName input value is treated as a literal value and not as executable code in the database.

Does the code use parameters in SQL statements?

If the code does not use stored procedures, make sure that it uses parameters in the SQL statements it constructs, as shown in the following example.
select status from Users where UserName=@userName
  
Check that the code does not use the following approach, where the input is used directly to construct the executable SQL statement by using string concatenation.
string sql = "select status from Users where UserName='"
           + txtUserName.Text + "'";
  

Does the code attempt to filter input?

A common approach is to develop filter routines to add escape characters to characters that have special meaning to SQL. This is an unsafe approach, and developers should not rely on it because of character representation issues.

Cross-Site Scripting

Code is vulnerable to cross-site scripting attacks wherever it uses input parameters in the output HTML stream returned to the client. Even before you conduct a code review, you can run a simple test to determine if your application is vulnerable. Search for pages where user input information is sent back to the browser. To perform this test, type text, such as XYZ, in form fields and test the output. If the browser displays XYZ or if you see XYZ when you view the HTML source, then your Web application is vulnerable to cross-site scripting. If you want to perform a more dynamic test, inject <script>alert('hello');</script>. This technique might not work in all cases because it depends on how the input is used to generate the output. The following questions can help you to identify vulnerable areas:
  • Does the code echo user input or URL parameters back to a Web page?
  • Does the code persist user input or URL parameters to a data store that could later be displayed on a Web page?

Does the code echo user input or URL parameters back to a Web page?

If you include user input or URL parameters in the HTML output stream, you might be vulnerable to cross-site scripting. Make sure that the code validates input and that it uses HtmlEncode or UrlEncode to validate output. Even if a malicious user cannot use your application's UI to access URL parameters, the attacker still may be able to tamper with them.
Reflective cross-site scripting is less dangerous than persistent cross-site scripting due to its transitory nature.
The application should not contain code similar to the following example.
Response.Write( Request.Form["name"] );
  
Instead, the application should contain code similar to the following.
Response.Write( HttpUtility.HtmlEncode( Request.Form["name"] ) );
  

Does the code persist user input or URL parameters to a data store that could later be displayed on a Web page?

If the code uses data binding or explicit database access to put user input or URL parameters in a persistent data store and then later includes this data in the HTML output stream, the application could be vulnerable to cross-site scripting. Check that the application uses HtmlEncode or UrlEncode to validate input and encode output. Pay particular attention to areas of the application that permit users to modify configuration or personalization settings. Also pay attention to persistent free-form user input, such as message boards, forums, discussions, and Web postings. Even if an attacker cannot use the application's UI to access URL parameters, a malicious user might still be able to tamper with them.


Use the following questions when you review your code's input and data validation:
  • Does the code validate data from all sources?
  • Does the code centralize its approach?
  • Does the code rely on client-side validation?
  • Does the code accept path or file-based input?
  • Does the code validate URLs?
  • Does the code use MapPath?

Does the code validate data from all sources?

Make sure that your code makes no assumptions about the validity of input data. Code should assume that input data is malicious. Use the following questions to guide your review.
  • Does the code validate form field input? The application should not contain code similar to the following example.
    <form id="WebForm" method="post" runat="server">
    <asp:TextBox id="txtName" runat="server"></asp:TextBox>
    </form>
      
    Instead, the text is validated using the RegularExpressionValidator control, as shown in the following example.
    <form id="WebForm" method="post" runat="server">
    <asp:TextBox id="txtName" runat="server" />
    <asp:RegularExpressionValidator 
       id="nameRegex"
       runat="server"
       ControlToValidate="txtName"
       ValidationExpression="^[a-zA-Z'.\s]{1,40}$"
       ErrorMessage="Invalid name" 
    /></form>
      
  • Does the code validate query string and cookie input? The application should use code similar to the following.
    // Request.QueryString
    // Instance method:
    Regex reg = new Regex(@"^[a-zA-Z'.\s]{1,40}$");
    Response.Write(reg.IsMatch(Request.QueryString.Get("Name")));
    
    // Static method:
    if (!Regex.IsMatch(Request.QueryString.Get("Name"),@"^[a-zA-Z'.\s]{1,40}$")) 
    {
      // Name does not match expression
    }
    
    // Request.Cookies
    // Instance method:
    Regex reg = new Regex(@"^[a-zA-Z'.\s]{1,40}$");
    Response.Write(reg.IsMatch(Request.Cookies.Get("Name")));
    
    // Static method:
    if (!Regex.IsMatch(Request.Cookies.Get("Name"),@"^[a-zA-Z'.\s]{1,40}$")) 
    {
      // Name does not match expression
    }
      
  • Does the code validate data that is retrieved from a database? Your application should validate this form of input, especially if other applications write to the database. Do not make assumptions about how thorough the input validation of the other application is.
    The application should not contain code similar to the following example.
    SqlConnection conn = new SqlConnection(connString);
    SqlCommand sqlCmd = new SqlCommand("SELECT CustomerID FROM Orders WHERE OrderID=1", conn);
    SqlDataReader dr = sqlCmd. ExecuteReader ();
    dr.Read();
    string s = dr[0].ToString();
    int val = Int32.Parse(TextBox1.Text);
      
    Instead, the code should contain code similar to the following.
    SqlConnection conn = new SqlConnection(connString);
    SqlCommand sqlCmd = new SqlCommand("SELECT CustomerID FROM Orders WHERE OrderID=1", conn);
    SqlDataReader dr = sqlCmd. ExecuteReader ();
    dr.Read();
    string s = dr[0].ToString();
    if (!(Int32.Parse(s) < 6))
         Response.Write("Throw an error");
    int val = Int32.Parse(TextBox1.Text);
      
  • Does the code validate Web method parameters? Web services are just as vulnerable as standard Web forms to input manipulation attacks like SQL injection. Make sure your code validates Web method parameters as shown here.
    [WebMethod]
    public decimal RetrieveAccountBalance(string accountId)
    {
      if (!Regex.IsMatch(accountId,@"^[a-zA-Z'.\s]{1,40}$")) 
      {
        // AccountID does not match expression
        // do not process request
      }
    }
      

Does the code centralize its approach?

For common types of input fields, examine whether or not the code uses common validation and filtering libraries to ensure that validation rules are performed consistently and it has a single point of maintenance.

Does the code rely on client-side validation?

Client-side validation can reduce the number of round trips to the server, but do not rely on it for security because it is easy to bypass. Validate all input at the server.
It is easy to modify the behavior of the client or just write a new client that does not observe the same data validation rules. Consider the following example.
<html>
<head>
<script language='javascript'>
function validateAndSubmit(form)
{
   if(form.elments["path"].value.length() > 0)
   {
      form.submit();
   }
}
</script>
</head>
<body>
<form action="Default.aspx" method="post">
<input type=text id=path/>
<input type=button onclick="javascript:validateAndSubmit(this.parent)" Value="Submit" />
</form>
</body>
</html>
  
In this example, client-side scripting validates that the length of the "path" is greater than zero. If the server processing of this value relies on this assumption to mitigate a security threat, then the attacker can easily break the system.

Does the code accept path or file-based input?

Determine whether your application uses names that are based on input to make security decisions. If it does, your code is susceptible to canonicalization issues. For example, does it accept user names, file names, or URLs? These are notorious for canonicalization issues because of the many ways that the names can be represented. If your application does accept names as input, make sure that they are validated and converted to their canonical representation before processing.
The application should use code similar to the following.
string fileName = Request.QueryString.Get("filename");      // myFile.txt
string path = Request.QueryString.Get("path");              // @"\mydir\";
string fullPath;
fullPath = System.IO.Path.GetFullPath(path);
fullPath = System.IO.Path.GetFullPath(fileName);
  

Does the code validate URLs?

The application should not contain code similar to the following example.
Uri siteUri = new Uri("http://www.contoso.com/");
// use custom ways of verifying if the uri is absolute
  
Instead, the application should contain code similar to the following.
Uri siteUri = new Uri("http://www.contoso.com/");
//use the .NET Framework Library's IsAbsoluteUri() method
if (siteUri.IsAbsoluteUri())
     //take appropriate action
  

Does the code use MapPath?

Review code for the use of MapPath. MapPath should be used to map the virtual path in the requested URL to a physical path on the server to ensure that cross-application mapping is not allowed.
The application should not contain code similar to the following example.
string mappedPath = Request.MapPath( inputPath.Text, 
                                       Request.ApplicationPath);
  
Instead, the application should contain code similar to the following.
try
{
  string mappedPath = Request.MapPath( inputPath.Text, 
                                       Request.ApplicationPath, false);
}
catch (HttpException)
{
  // Cross application mapping attempted.
}
  

Authentication

Authentication is the process of determining caller identity. Many ASP.NET Web applications use a password mechanism to authenticate users, where the user supplies a user name and password in an HTML form. When you review authentication code, determine whether user names and passwords are sent in plain text over an insecure channel, analyze how user credentials are stored, examine how credentials are verified, and see how the authenticated user is identified after initial logon. Table 4 lists the authentication vulnerabilities and their corresponding security implications. Authentication Vulnerabilities and Implications Weak passwords:-Passwords can be guessed and dictionary attacks can increase. Clear text credentials in configuration files:-Insiders who can access the server or attackers who exploit a host vulnerability to download the configuration file have immediate access to credentials. Passing clear text credentials over the network:-Attackers can monitor the network to steal authentication credentials and spoof identity. Over-privileged accounts:-The risks associated with a process or account compromise increase. Long sessions:-The risks associated with session hijacking increase. Mixing personalization with authentication:-Personalization data is suited to persistent cookies. Authentication cookies should not be persisted. The following questions can help you to identify vulnerable areas:
  • Does the code enforce strong user management policies?
  • Does the code restrict the number of failed login attempts?

Does the code enforce strong user management policies?

To determine if the application enforces strong user management policies, consider the following questions:

Forms Authentication

If you use forms authentication, you should review your code to make sure that you properly secure the authentication ticket and that passwords are stored securely in persistent stores. You should also review the code that accesses the user store to make sure that there are no vulnerabilities. Failing to protect authentication tickets is a common vulnerability that can lead to unauthorized spoofing and impersonation, session hijacking, and elevation of privilege. Table 5 lists the forms authentication vulnerabilities and their corresponding security implications. The following questions can help you make sure that the forms authentication implementation is protected.
  • Does the code use membership?
  • Does the code persist forms authentication cookies?
  • Does the code reduce ticket life time?
  • Does the code use protection="All"
  • Does the code restrict authentication cookies to HTTPS connections?
  • Does the code use SHA1 for HMAC generation and AES for encryption?
  • Does the code use distinct cookie names and paths?
  • Does the code keep personalization cookies separate from authentication cookies?
  • Does the code use absolute URLs for navigation?
  • How does the code store passwords in databases?
  • Does the code partition the Web site into restricted and public access areas?

Does the code use membership?

Determine if the code uses ASP.NET 2.0 membership with forms authentication. This reduces the amount of code that developers need to write to manage user accounts and verify user credentials, and it helps to ensure that the application supports strong user management policies.

Does the code persist forms authentication cookies?

The code should not persist authentication cookies because they are stored in the user's profile and can be stolen if an attacker gets physical access to the user's computer. The code should not do the following:
  • Set the DisplayRememberMe property of the Login control to true.
  • Request a persistent cookie when calling the RedirectFromLoginPage or SetAuthCookie methods of the FormsAuthentication class.
  • Pass true to the FormsAuthenticationTicket constructor to request a persistent cookie.

Does the code reduce ticket life time?

If the code cannot use secure sockets layer (SSL) to protect the forms authentication ticket, does it reduce ticket life time? The default timeout for an authentication cookie is 30 minutes. Review the <forms> definition and consider reducing the timeout as shown in the following example.
<forms 
    timeout="10" 
    slidingExpiration="true" ... />
  

Does the code use protection="All"?

Make sure that your forms authentication tickets are encrypted and integrity checked by setting protection="All" on the <forms> element. This is the default setting, and you can view this in the Machine.config.comments file.
<forms protection="All" ... />
  
Make sure that your application-specific Web.config file does not override this default setting.

Does the code restrict authentication cookies to HTTPS connections?

Ensure that you use SSL with all pages that require authenticated access, and restrict forms authentication tickets to SSL channels by setting requireSSL="true" on the <forms> element, as shown in the following example.
<forms loginUrl="Secure\Login.aspx"
       requireSSL="true" ... />
  
By setting requireSSL="true", you set the secure cookie property that determines whether browsers should send the cookie back to the server. With the secure property set, the browser only sends the cookie to a secure page that is requested by using an HTTPS URL.
Note   If you are using cookieless sessions, you must ensure that the authentication ticket is never transmitted across an unsecured channel.

Does the code use SHA1 for HMAC generation and AES for encryption?

Verify that the application does not override the default algorithm settings documented in the Machine.config.comments file, as shown in the following example.
<machineKey 
   ...
   decryption="Auto" 
   validation="SHA1" />
  

Does the code use distinct cookie names and paths?

Make sure that the code uses unique name and path attribute values on the <forms> element, as shown in the following example.
<forms name="YourAppName"
       path="/FormsAuth" ... />
  

Does the code keep personalization cookies separate from authentication cookies?

The code should avoid creating a persistent authentication cookie and loading it with user preference data, as shown in the following example.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1,
                            Context.User.Identity.Name,
                            System.DateTime.Now,
                            System.DateTime.Now.AddMinutes(15),
                            true, 
                            userPreferenceData, 
                            roleStr );
  
Instead, create non-persistent authentication cookies and create a separate personalization cookie, as shown in the following example
// Authentication ticket without user preferences
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1,
                                        Context.User.Identity.Name,
                                        DateTime.Now,
                                        DateTime.Now.AddMinutes(15),
                                        false,
                                        roleStr);
// Create the preferences cookie.
Response.Cookies.Add(new HttpCookie( cookieName, userPreferenceData ));
  

Does the code use absolute URLs for navigation?

Make sure that the code uses absolute links such as http://servername/appname/publicpage.aspx when redirecting from an HTTPS page to an HTTP page. Also verify that when your code redirects to a secure page (for example, the logon page) from a public area of your site, it uses an absolute HTTPS path, such as https:// servername/appname/secure/login.aspx instead of a relative path, such as restricted/login.aspx. For example, if your Web page provides a logon button, it should use the following code to redirect to the secure login page.
private void btnLogon_Click( object sender, System.EventArgs e )
{
  // Form an absolute path using the server name and v-dir name
  string serverName = 
         HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);
  string vdirName = Request.ApplicationPath;
  Response.Redirect("https://" + serverName + vdirName + 
                    "/Restricted/Login.aspx");
}
  

How does the code store passwords in databases?

Check how your code stores passwords. Passwords should be stored as non-reversible hashes with an added random salt value. If your code uses the SqlMembershipProvider for storing passwords, make sure that the passwordFormat attribute is set to Hashed. The configuration setting should look similar to the following.
<membership>
  <providers>
    <add passwordFormat="Hashed" ... />
  </providers>
</membership>
  

Does the code partition the Web site into restricted and public access areas?

If your Web application requires users to complete authentication before they can access specific pages, make sure that the restricted pages are placed in a separate directory away from publicly accessible pages. This allows you to configure the restricted directory to require SSL. It also helps you to ensure that authentication cookies are not passed over unencrypted sessions by using HTTP. The following questions can help you to identify vulnerable areas:
  • How does the code protect access to restricted pages?
  • How does the code protect access to page classes?
  • Does the code use Server.Transfer?

How does the code protect access to restricted pages?

If the application uses Windows authentication, has it configured NTFS permissions on the page (or the folder that contains the restricted pages) to allow access only to authorized users? Is the <authorization> element configured to specify which users and groups of users can access specific pages?

How does the code protect access to page classes?

Are principal permission demands added to classes to specify which users and groups of users can access the classes?

Does the code use Server.Transfer?

Make sure that if the code uses Server.Transfer to transfer a user to another page, the currently authenticated user is authorized to access the target page. If the code uses Server.Transfer to transfer to a page that the user is not authorized to view, the page is still processed. This is because Server.Transfer uses a different module to process the page rather than making another request from the server, which would force authorization. The code should not use Server.Transfer if security is a concern on the target Web page. It should use HttpResponse.Redirect instead.

Code Access Security

Code access security is a resource-constraint model designed to restrict the types of system resources that the code can access and the types of privileged operations that the code can perform. These restrictions are independent of the user who calls the code or the user account under which the code runs. If the code you are reviewing operates in partially-trusted environments and uses explicit code access security techniques, review it carefully to make sure that code access security is used appropriately. Table 7 shows possible vulnerabilities that occur with improper use of code access security.

Does the code use link demands or assert calls?

Look closely at each use of LinkDemand and Assert calls. These can open the code to luring attacks because the code access stack walk will be stopped before it is complete. While the use of these calls is sometimes necessary for performance reasons, make sure that there can be no un-trusted callers higher in the stack that could use this method's LinkDemand or Assert call as a mechanism for attack.

Does the code use AllowPartiallyTrustedCallersAttribute?

Pay particular attention if the code you are reviewing allows partially trusted callers by including the following attribute.
[assembly: AllowPartiallyTrustedCallersAttribute()]
  
This allows the assembly to be accessible from calling code that is not fully trusted. If the code you are reviewing then calls an assembly that does not allow partially trusted callers, a security issue could result.

Does the code use potentially dangerous permissions?

Check the code for requests to potentially dangerous permissions such as: UnmanagedCode, MemberAccess, SerializationFormatter, SkipVerification, ControlEvidence / ControlPolicy, ControlAppDomain, ControlDomainPolicy, and SuppressUnmanagedCodeSecurityAttribute. The following code example uses SuppressUnmanagedCodeSecurityAttribute. You should flag this as a dangerous practice.
[DllImport("Crypt32.dll", SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]
[SuppressUnmanagedCodeSecurity]
private static extern bool CryptProtectData(
  ref DATA_BLOB pDataIn, 
  string szDataDescr, 
  ref DATA_BLOB pOptionalEntropy,
  IntPtr pvReserved, 
  ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, 
  int dwFlags, 
  ref DATA_BLOB pDataOut);
  

Does the code give dependencies too much trust?

Without explicit safeguards, it is possible for an attacker to trick your code into loading a malicious library instead of trusted code. Check to see if all the loaded assemblies are strongly named; this step ensures that tampering cannot occur. Without strong names, your code could be calling into malicious code without knowing it. The use of native code libraries makes this harder to do so be cautious about trusting native code implicitly. Native libraries can be checked with a hash or a certificate. Additionally you should make sure that all libraries are loaded with a complete path in order to avoid canonicalization attacks. Also check whether delay signing is enabled. Delay signing is generally regarded as a good practice because it helps protect the confidentiality of the private key that will be used for signing the component:
[assembly:AssemblyDelaySignAttribute(true)]



Session Modes and Session Provider

Session ID
Asp.Net use 120 bit identifier to track each session. This is secure enough and can't be reverse engineered. When client communicate with server, only  session id is transmitted, between them. When client request for data, ASP.NET looks on to session ID and retrieves corresponding data. This is done in following steps, 
Client hits web site and some information is stored in session.

Storing and Retrieving values from Session

Storing and Retrieving values in session are quite similar with ViewState. We can interact with Session State with  System.Web.SessionState.HttpSessionState class, because this provides built in Session Object with Asp.Net Pages.


//Storing UserName in Session
       Session["UserName"] = txtUser.Text;

Now, let see how we can retrieve values from 
Session

Advantages and Disadvantages of Sessions?


Following are the basic advantages and disadvantages of using session. I have describe in details with each type of session at later point of time.
Advantages : 
  • It helps to maintain user states and data to all over the application.
  • It can easily be implemented and we can store any kind of object. 
  • Stores every client data separately. 
  • Session is secure and transparent from user.