Simple ASP. NET Forms Identity Authentication

Source: Internet
Author: User
Tags httpcontext ticket sql server management

Read a few cattle of this aspect of the article, oneself also do a bit, want to need to summarize. Of course, the quality of my article can not be compared with others, just write to never contact the knowledge point of friends.

Authentication of the website I used to know only the session, and occasionally found that some cattle advocates using forms, Microsoft also recommended this method. See Using the session as an identification problem

Asp. NET is configuration->system.web->authentication specified in the Web. config file, such as

[HTML]View PlainCopyprint?
    1. <authentication  mode= "Forms"  >  
    2.           <forms cookieless= "usecookies" name=" Logincookiename "loginurl=" ~/ Default.aspx "></forms>   
    3. </authentication>  

Mode= "Forms" represents an instant form identity authentication method. There is also none, Passport, Windows optional, the other two are not yet known, the way Windows and SQL Server Management Stdio Windows authentication is a reason. When the site's IP is localhost, the site does not log on to the status of instant login, and only the other IP, the login site only need to enter the user name, password. And this article is about forms authentication.

The program is divided into three steps: Log in to the Login.aspx page to write a cookie, the user accesses the Default.aspx program to read the cookie data and give the user the corresponding role, the program view Global.asax see if the user has access to the page.

1. Processing after verification of identity information on the login page

[CSharp]View PlainCopyprint?
    1. var ticket = new FormsAuthenticationTicket (
    2. 1, name, DateTime.Now, DateTime.Now.AddMinutes (5),true, "admin"); Constructing user Tickets
    3. String Cookievalue =formsauthentication.encrypt (ticket);
    4. HttpCookie cookie =new HttpCookie (Formsauthentication.formscookiename, cookievalue);
    5. Response.Cookies.Remove (cookies. Name);
    6. RESPONSE.COOKIES.ADD (cookie);

FormsAuthenticationTicket Constructor Parameter Description: Version number, ticket name, construction time, expiration time, whether persisted (if true means that the ticket is stored in a persistent cookie, that is, a cross-browser session), User-defined data (here is a list of logged-in user roles, separated by ",").

Then encrypt the note into the cookie

This is what the web Developer in FF sees, and value is the result of the encryption. Path is the pointer to a directory or page under the site, and "/" represents the entire site. HttpOnly If True indicates that the script cannot be accessed, which prevents some XSS attacks from using HttpOnly to enhance Web application security

2. What to add in Global.asax

[CSharp]View PlainCopyprint?
  1. void Application_postauthenticaterequest (Object sender, EventArgs e)
  2. {
  3. HttpApplication App = (HttpApplication) sender;
  4. HttpContext context = App.context; //Get the HttpContext object associated with this HTTP request
  5. if (context. request.isauthenticated) //authenticated user for role processing
  6. {
  7. FormsIdentity Id =context.  User.Identity as formsidentity;
  8. FormsAuthenticationTicket Ticket =id.ticket; //Get an authentication ticket
  9. string[] Roles =ticket.userdata.split (', '); //Convert the role data in the authentication ticket to a string array of custom user data previously stored in the cookie
  10. Context. User = New GenericPrincipal (Id, Roles); //The original identity plus role information creates a new GenericPrincipal that represents the current user, so that the current user has role information
  11. }
  12. }

Application_postauthenticaterequest is an event in an ASP. NET pipeline that is triggered when a page is requested. The detailed knowledge remains to be learned.

This step can also define a class that implements the IHttpModule interface, in which this is written:

[CSharp]View PlainCopyprint?
    1. Public void Init (Httpapplicationapp)
    2. {
    3. App. Postauthenticaterequest +=application_postauthenticaterequest;
    4. }
    5. Voidapplication_postauthenticaterequest (Object sender, EventArgs e)
    6. {
    7. //...
    8. }

The user has stored the cookie on the browser after the first step of login, and once again requests another page, after the Global.asax in the Application_postauthenticaterequest processing, in the context. The role information is stored in user. Here we construct the context. User has a private User field, this field can only use the IsInRole method to determine whether the user belongs to a certain, we can not modify it, and this field is always empty at the time of initialization, we have to use this way to the user to attach role information.

3. Content in the configuration file

[HTML]View PlainCopyprint?
  1. <system.web>
  2. <compilationdebugcompilationdebug="true" targetframework="4.0"/>
  3. <httpRuntime requestvalidationmode="2.0"/>
  4. <!--I created the module folder under the App_Code folder in website and added the MyModule class--
  5. <httpmodules>
  6. <addnameaddname= "MyModule"type= "MyModule"/>
  7. </httpmodules>
  8. <authentication mode="Forms">
  9. <!--name is the user name that holds the cookie information, loginurl is the specified login page (which jumps to this page when the user does not have permission to access the location-restricted page below), and timeout is the cookie expiration time-
  10. <forms cookieless="usecookies" name="Logincookie" loginurl= "~/login.aspx" timeout="5"></forms>
  11. </Authentication>
  12. <authorization>
  13. <allowusersallowusers="*"/>
  14. </Authorization>
  15. </system.web>
  16. the path in <!--location can be a folder or a page that restricts access to certain pages. The following indicates that Default.aspx is only developed for the admin role. Note that if you restrict certain pages from being accessible only to certain roles, you must finally add <deny users= "*"/>-->
  17. <location path="default.aspx">
  18. <system.web>
  19. <authorization>
  20. <allow roles="admin"/>
  21. <deny users="*"/>
  22. </Authorization>
  23. </system.web>
  24. </location>

After the program executes the second step, see if the role has access to the request page in the configuration file.

Source

Reference article: Elaborating on the use of role-based Forms authentication in ASP.

Also highly recommended a blog: http://www.cnblogs.com/fish-li/

Simple ASP. NET Forms Identity Authentication

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.