ASP. NET Forms authentication to fix cookie and seesion failure time

Source: Internet
Author: User

In website development, user authentication generally uses ASP. NET Forms authentication to verify that tickets are stored in cookies.

The session method stores authentication information in the memory. If the virtual host you use allocates a small amount of memory to you, the session will expire soon and you are required to log on again, if the user is entering information and is asked to log on again, the feeling of anger can be imagined.

Cookies are stored on the user's client. However, you will also encounter failures. Let's take a look at them one by one.

In ASP. NET Forms authentication, we usually use the login control that comes with ASP. NET for verification. In the Web. config file, all forms settings are set as default. Now, the problem is coming.

1. Why did I log out in about half an hour after I clicked "remember me?

2. Why do I log out again one or two days later?

This is a lot of issues encountered in Forms authentication. Next, I will give a detailed explanation of these two questions: for question 1, I will first clarify the differences between ticket and cookie. A cookie is a container used to store things. It is stored on the client. Ticket is the specific data used to indicate the specific authentication information, which is placed in the cookie container. Therefore, the following happened during our verification. First, ticket is created, which contains the username and other information, and has an expiration time.

Then, the cookie is created, and it also has an expiration time. Finally, save ticket in the cookie and send the cookie to the client's browser. After reading this, I think the problem is quite clear. The user's log out is due to the expiration time. But who has expired? In our ASP. net web. in config settings, timeout is the cookie expiration time (note that the default value is 30 minutes), while ticket has an unlimited expiration time because we chose "remember me ". that's why I clicked "remember me ".

However, after about 30 minutes, I was still logged out because we didn't set the cookie timeout. ticket and cookie, as long as one of them does not never expire, we cannot never expire.

When we solve problem 1 (if we manually set timeout = "4000000"), we encountered problem 2 again. What is the reason for this? This should start with ticket's encryption and decryption mechanism. ASP. NET uses a machinekey to encrypt cookies. This machinekey is randomly generated at application startup by default. ASP. NET then uses the same machinekey for Cookie decryption. This is because the key is randomly generated during application startup, which leads to problem 2. Imagine what if application recycle is restarted?

ASP. NET will generate another key for decryption, and the previous cookie will no longer be valid, which is the cause of problem 2. With this in mind, the solution to the second problem is simple. manually set a specific key. for example: <machinekey validationkey = "88cb6ca6cf403c5fbb41c2f62bb7fcfca05de7be" decryptionkey = "b8a7cf3816109176" validation = "sha1"/>

Steps for implementing Asp.net Forms authentication

For application authentication, you have always compiled your own login form. In the CS file of the form, you can determine whether the user's login is legal. If so, the user name is saved in the cookie. Then, inherit all pages from a base page like baseform, and add judgment in the page_load event of this page to determine whether the user has logged on based on the cookie, if you have not logged on, the logon page is displayed.
Recently I made an Internet-connected website and thought of security issues. After reading some documents, I thought that the standard forms authentication method provided by Asp.net was adopted. After studying this, write down the operation steps for reference in the future (a very important function of blog is to save previous learning accumulation)
1. Modify the Web. config file. If vs2005 does not have this file by default, the system will prompt you whether to add this file during debugging. In the <system. Web> section of the web. config file, add the following three parts:

 <authentication mode="Forms">
<forms loginUrl="default.aspx" name=".ASPXFORMSAUTH">
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
<machineKey
validationKey="AutoGenerate,IsolateApps"
decryptionKey="AutoGenerate,IsolateApps"
validation="SHA1"
decryption="Auto" />

 

 

The above three parts are marked with different colors. The first part is to set the Authentication Mode of the application. The default is windows. If your system is used in the LAN, in addition, if the LAN is working in the domain mode, Windows authentication will be very effective. If multiple B/S are used for authentication in Windows mode, they can even achieve single-point login easily. However, Forms authentication is more common, although it has poor security. There is a forms section under the authentication section, where you can fill in the page for performing your authentication and the cookie name used to store the authentication. If you do not enter the cookie name, Asp.net assigns. aspxformsauth as the cookie name by default.
The second part is authorization. You can configure to allow or deny some users or roles to access your application. Which of the following is deny and allow can be used with wildcards? , * Allows us to easily configure a lightweight and simple authentication system. For detailed configuration information, refer to the help document of Asp.net, which is not described in detail here.
The third part is the encryption/decryption algorithm used to configure access cookies. With this algorithm, the cookie should be safe.
2. log on to and save the cookie information.

 Formsauthenticationticket authticket = new formsauthenticationticket (1, cookieinfo, datetime. Now, datetime. Now. addhours (20), false, userdata); // user data
String encryptedticket = formsauthentication. Encrypt (authticket); // Encryption
// Store the cookie
Httpcookie authcookie = new httpcookie (formsauthentication. formscookiename, encryptedticket );
Authcookie. expires = authticket. expiration;
Response. Cookies. Add (authcookie );

 

 

First, create an identity ticket, which stores the user's name and cookie expiration time. In addition, you can save some additional data, such as the role played by the user. Note that userdata is used to save some extra data, such as a role. However, if I do not have any data, a null value is usually passed in, however, if you want to encrypt and save the cookie information, the null value cannot be passed here. You can pass a "" value. If null is passed, a null value is returned when string encryptedticket = formsauthentication. Encrypt (authticket); is executed, so that an incorrect encryption cookie value is generated. If you want to save the cookie for a long time, you need to set an expiration time for the cookie.
3. Read the Cookies stored in the computer.
The application_authenticaterequest event exists in the global. asax file, which is executed when all server requests are executed. Therefore, we can read cookies and decrypt them. The following is the sample code:

 1 protected void application_authenticaterequest (Object sender, eventargs E)
2 {
3 string cookiename = formsauthentication. formscookiename; // obtain the cookie name from the verification ticket.
4 // obtain the cookie.
5 httpcookie authcookie = context. Request. Cookies [cookiename];
6 if (null = authcookie)
7 return;
8 formsauthenticationticket authticket = NULL;
9 // obtain the verification ticket.
10 authticket = formsauthentication. decrypt (authcookie. value );
11 if (null = authticket)
12 return;
13
14 // The userdata of the authentication ticket stores the user role information.
15 // userdata is used to store user-defined information. This is used to store user roles.
16 string [] roles = authticket. userdata. Split (New char [] {','});
17 formsidentity id = new formsidentity (authticket );
18 genericprincipal principal = new genericprincipal (ID, roles );
19 // grant the generated verification ticket information and role information to the current user.
20 context. User = principal;
21}

 

 

After you encrypt and store cookies, you must decrypt them before using them.
4. Read the cookie value on each page. You can use the following statement to read the cookie value. Httpcontext. Current. User. Identity. Name

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/vasun/archive/2009/12/29/5100743.aspx

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.