There are three kinds of authentication of ASP.NET, namely "Windows | Forms | Passport", which is mostly used in Forms to verify the most, and most flexible. The Forms verification method provides good support based on user authentication authorization, can verify the user's identity by a login page, send this user's identity back to the client's cookie, then this user will access this web application will be along with this Identity cookie is sent together to the server. The authorization settings on the server can be controlled for different users' access authorizations according to different directories.
The problem is, it is actually used in the use of character, or based on the role, or based on the authentication and authorization of the user group. For a website, the general verification authorization mode should be like this: according to the actual needs to divide the user into different identities, the role, or the user group, the verification process must not only verify the identity of this user, but also verify It belongs to which role. The access authorization is set according to the role, and some of the characters can access which resources can be accessed. If the user's authorization access will be a very unpractory practice, there are many users, but it is also possible to increase or decrease at any time, and it is impossible to increase access authorization for increasing new users at any time in the configuration file.
Let's take a look at the process of Forms.
Forms Authentication Basic Principle:
One authentication
To use Forms authentication, you must first make the corresponding settings in Web.config in the application root directory:
Where
Let's take a look at which information contains, let's take a look at the FormsauthenticationalTicket class: cookiepath: Returns the path to the cookie. Note that the path to the form is set to /. Since the form is case sensitive, this is a protective measures taken to prevent the case where the URL in the site is inconsistent. This uses expiration when refreshing cookies: Get the date / time of the cookie expired. ISPERSISTENT: Returns true if you have already issued a lasting cookie. Otherwise, the authentication cookie will limit within the browser lifecycle. Issuedate: Get date / time that originally issued a cookie. Name: Gets the username associated with authentication cookies. UserData: Get the application definition string stored in the cookie. Version: Returns the byte version number for future use.
2. LoginURL in the
3. Timeout and path in the "Forms> tab are provided with authentication tickets to the cookie expiration time and default path. The above is based on Forms authentication process, which completed confirmation of the user identity. Here is an access authorization based on Forms authentication.
Second visit license
Verify the identity, is to use this identity, according to different identities, we can do different operations, process, the most common is to perform different identities, Forms authentication provides such functions. Forms authorization is a directory-based, you can set access to a directory, for example, these users can access this directory, those users cannot access this directory. Similarly, the authorization setting is set in the web.config file in the directory you want to control:
The
At runtime, the authorization module iterates through
So how do these USER and ROLES get? Let's take a look at the detailed process of authorization:
1. Once a user accesses this website, log in to confirm the identity, and the Cookie of the authentication ticket is also written to the client. After that, this user applies for this web page, and the authentication ticket is sent to the server. At the server, ASP.NET assigns an HTTPApplication object to handle this request. After the httpapplication.authenticateRequest event, the security module has established a user ID, which is that the user's identity has been built, this identity It is completely cookie created by the authentication ticket sent back by the client. 2. User identity In the httpContext.user property, you can get the HTTPContext object associated with this page through page.context in the page. For Forms authentication, the httpContext.user property is an object of GenericPrincipal, and GenericPrincipal has only one public property Identity. It is a private m_role property. It is a string [] type. The user is the array belonging to which Role, there is an open public Method is ISINROLE (String Role) to determine if this user belongs to a role. Since the authentication ticket is not available in the cookie of the authentication ticket, it is said that the Forms authentication ticket does not provide this user's role information, so for Forms verification, the M_Role properties of the genericprincipal user objects received in the server are always empty. 3. GenericPrincipal. Identity property is an object of a FormSIDETY type. This object has a Name property, which is the name of this user. Access authorization is to perform this property as a User to authorize authentication. FormSident has a property, which is a Ticket property. This property is the authentication ticket FormSauthenticationalTicket type, which is previously written to the client's authentication ticket. After getting the authentication ticket FormsAuthenticationalTicket object, it is not a long-lasting authentication. If you want to update this authentication ticket according to the validity period set by the timeout property in Web.config (to avoid endanger performance After more than half of the specified time, this cookie can result in the loss of accuracy. Persistent cookie does not timeout.) 4. Before the httpapplication.resolverequestCache event, ASP.NET starts obtaining the user request page, establishing Httphandler control point. This means that at the httpapplication.resolverequestCache event to verify user access, see if this user or role has permission to access this page, then change this user's identity or role in this request lifecycle. . The above is the whole process of Forms verification, it can be seen that this Forms verification is based on the user's, and there is no direct support for the validation of the role. The name attribute in the FormsauthenticationalTicket is the user's name, in fact, there is still a property userData, which can be written to customized data by the application, we can use this field to store the role-based information based on role verification the goal of.
Forms authentication based on role authorization
One authentication
Is the same or the same as Web.Config's
1. First, create an authentication ticket PUBLIC FORMSAUTHENTICTICKET (int version, // set to 1String Name, //), set to the user, // user, set to DateTime.now datetime expression, // Expired time BOOL ISPERSISTENT, // Whether it is persistent (as needed, if it is set to persistence, when emitting cookies, cookie's Expires setting must be set) String UserData, // Here It is ready to use a comma-divided role string string cookiepath / / set to "/", which is consistent with the path to the cookie, because refreshing cookies want to use this path);
FormsauthenticationalTicket Ticket = New FormsauthenticationTicket (1, "Kent", DateTime.Now, DateTime.Now.addminutes (30), False, Userroles, "/");
2. Generate the authentication ticket Cookie2.1 authentication ticket encryption sequence into a string string HashTicket = FormsAuthentication.Encrypt (Ticket); 2.2 generating cookieHttpCookie UserCookie = new HttpCookie (FormsAuthentication.FormsCookieName, HashTicket); FormsAuthentication.FormsCookieName is To get the name of the authentication cookie set in Web.config, default is ".aspxauth". If the ISPERSIStent property in the authentication ticket is set to last class, this cookie's Expires property must set, so this cookie will not In the cookie file for your lasting cookie. 3. 3. Output the authentication ticket cookie to the client via response.cookies.add (userCookie) to add authentication ticket cookies to the output cookie collection, send to the client . 4. Redirect to the initial test page for the user.
Verify partial code (this part of the code is on the login.aspx page, click the login button event processing code):
private void Buttonlogin_Click (object sender, System.EventArgs e) {string user = TextBoxUser.Text; // read the user name string password = TextBoxPassword.Text; // read the password if (Confirm (user, password) == true) // confirm the legitimacy of the method used to authenticate users {string userRoles = UserToRole (user); // call the method to get the role UserToRole string FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1, user, DateTime.Now, DateTime.Now.AddMinutes ( 30), false, userRoles, "/"); // build the object authentication ticket string HashTicket = FormsAuthentication.Encrypt (ticket); // encryption sequence is a string of tickets validation HttpCookie userCookie = new HttpCookie (FormsAuthentication.FormsCookieName, HashTicket ); // Generate cookie context.response.cookies.add (userCookie); // Output cookie context.Response.Redirect (Context.Request ["ReturnURL"]); // Redirect to the initial page to user application} else { // User identity is not confirmed when the code}} // This method is used to verify the user legality private bool confirm (String User, String Password) {// The corresponding code} // This method is used to obtain the user corresponding All role split a string private usetertorole (String Use) r) {// Corresponding code} II Based on role access authorization
What we have to do this is that the information saved in the userData saved in the user-saved authentication ticket is restored to the GenericPrincipal object indicating the user's identity (remember, the genericprincipal object is only included during the original verification process. User information, no role information) A HTTP request, httpapplication.authenticateRequest event indicates that the security module has established a user ID, that is, the user's identity has been established in the web end, after this event we can get the user identity Information. Before the httpapplication.resolverequestCache event, ASP.NET starts obtaining the page of the user request, establish an HTTPHANDLER control point, then verify the user's permissions, so restoring the user role work can only be in the httpApplication.authenticateRequest event and HTTPAPLICATION.ResolveRequestCache events are done in the process. We choose to do this in the Application_AuthorizeRequest event, you can handle all the events of HTTPApplication in the global.asax file, the code is as follows:
protected void Application_AuthorizeRequest (object sender, System.EventArgs e) {HttpApplication App = (HttpApplication) sender; HttpContext Ctx = App.Context; // Get the current Http request associated HttpContext object if (Ctx.Request.IsAuthenticated == true) // Verified users conduct role processing {FormSidentity ID = (Formentity) ctx.user.Identity; FormSauthenticationalTicket Ticket = id.ticTicket; // get the authentication ticket String [] Roles = Ticket.userData.split (', '); // Transfer the role data in the authentication ticket into a string array ctx.user = new genericprincipal (id, roles); // Add the original Identity plus the role information to new genericprincipal represents the current user, so current The user has a Role information}} Accessor has the user and role information, which can use Role to control the user's access rights in Web.config.