ASP. NET Forms Verification

Source: Internet
Author: User

ASP. NET Forms authentication

User verification is a required module for each project. Because it has not been met for a long time, today, a blank mind is written for user verification. As a result, I had a discussion with a colleague. At night, I decided to record the results of the discussion for later needs. There are several methods for user authentication in ASP. NET: Windows authentication, Forms authentication, and Passport authentication. Of course, users can also customize and verify methods, and Forms verification is the most commonly used method. This is also the verification method to be discussed today.

For ASP. NET Forms authentication, you must first configure the web. config file and configure the authentication node as Forms authentication, which is Windows authentication by default. When modifying the configuration file, pay attention to the Case sensitivity. Because the XML file is case sensitive, the modified authentication node is shown below, which also contains some form configuration parameters.

  1. <authenticationmodeauthenticationmode="Forms"> 
  2. <forms 
  3. protection="All" 
  4. timeout="20" 
  5. name=".XDOTNET" 
  6. loginUrl="SignIn.aspx" 
  7. defaultUrl="Default.aspx" 
  8. path="/" 
  9. requireSSL="false" 
  10. enableCrossAppRedirects="false" 
  11. > 
  12. </forms> 
  13. </authentication> 

The attributes of forms nodes will be used later to introduce the relevant members of the FormsAuthetication class. User verification, as its name implies, verifies the rationality of a user. When a user logs on to a website, it verifies that the entered user name and password are consistent with the data stored in the database. In fact, it is very simple, there is a fast method, this verification method is very suitable for the background management verification, because when we close the browser, the verification will become invalid.

  1. publicstaticboolValidUser(stringuserName,stringpassword)  
  2. {  
  3. if(!string.IsNullOrEmpty(userName)&&!string.IsNullOrEmpty(password))  
  4. {  
  5. password=FormsAuthentication.HashPasswordForStoringInConfigFile(password,"MD5");  
  6. stringrealPassword=Users.GetUser(userName).Password;  
  7. if(string.Compare(password,realPassword,true)==0)  
  8. {  
  9. FormsAuthentication.SetAuthCookie(userName,false);  
  10. returntrue;  
  11. }  
  12. }  
  13. returnfalse;  

The above method can verify the data verification of the Password encrypted with 32-bit MD5. The Users. GetUser (string) method is to obtain the user instance from the database by using the user name. When the user is reasonable, an authentication ticket will be created for the user using the FormsAuthentication. SetAuthCookie method) and added to the Cookie set or URLcookieless of the response ). In this way, the user authentication process is implemented. How can we get the user verification? Microsoft keeps encapsulating programs and making them foolish. Of course, it is very easy to get the current user to pass the verification. The Code is as follows:

  1. public static bool IsAuthenticated()   
  2. {  
  3. return HttpContext.Current.User.Identity.IsAuthenticated;  

Is it easy? When the user only needs to manage the verification in the background) The verification is okay as long as the two steps are taken. When the user logs on, such as calling the ValidUser method, when loading the page, the IsAuthenticated method is used to determine whether the current user has passed verification. Such a user verification module is complete, but in the modern network, users are quite valuable, and every website wants to retain a lot of users; sometimes some items can only be viewed by Members, and so on. This requires better verification. After closing the browser, the user is still in the verified status for a specific period of time. In this case, you need to operate and set the authentication ticket FormsAuthenticationTicket. The Code is as follows:

  1. Public static bool ValidUser (string userName, string password)
  2. {
  3. If (! String. IsNullOrEmpty (userName )&&! String. IsNullOrEmpty (password ))
  4. {
  5. Password=FormsAuthentication. HashPasswordForStoringInConfigFile (password, "MD5 ");
  6. StringRealPassword=Users. GetUser (userName). Password;
  7. If (string. Compare (password, realPassword, true) = 0)
  8. {
  9. FormsAuthenticationTicketTicket=NewFormsAuthenticationTicket (1,
  10. UserName,
  11. DateTime. Now,
  12. DateTime. Now. AddMinutes (20 ),
  13. False,
  14. Null // You can split Roles into strings by "," and write them into cookies.
  15. );
  16. StringData=FormsAuthentication. Encrypt (ticket );
  17. HttpCookieCookie=NewHttpCookie (FormsAuthentication. FormsCookieName, data );
  18. Cookie. Path=FormsAuthentication. FormsCookiePath;
  19. Cookie. Domain=FormsAuthentication. CookieDomain;
  20. Cookie. Expires=Ticket. Expiration;
  21. HttpContext. Current. Response. Cookies. Add (cookie );
  22. Return true;
  23. }
  24. }
  25. Return false;
  26. }

The FormsCookiePath and CookieDomain in the Code are obtained from the configuration file. Other FormsAuthentication members can access MSDN (FormsAuthentication ). We can also use the HttpContext. Current. User object to determine the Current User's status, or use the IsInRole method to determine the User's role. After verifying the User, add the User to the User object of the current request in the Http context HttpContext. The Code is as follows:

  1. FormsIdentity identity = new FormsIdentity(ticket);  
  2. GenericPrincipal user = new GenericPrincipal(identity, new string[] { });  
  3. HttpContext.Current.User = user; 

This completes the entire process of ASP. NET Forms authentication. As for checking the user's Cookie to determine whether the user has a record status such as record 1 month, 1 day, 1 year, etc.), you can judge and write it in the pipeline, and I will not go into details here. OK. Because of the time, record this. If there is any error or better method, please point it out. Thank you.

  1. Analysis of Theme functions in ASP. NET development skills
  2. ASP. NET Dynamic Compilation
  3. Analysis on ASP. NET supported by Apache
  4. Introduction to ASP. NET Server standard controls
  5. Analysis on SQL Server Database Backup Recovery in ASP. NET

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: 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.