There are three of asp.net authentication, respectively, "Windows | Forms | Passport ", which is also the most used in forms verification and the most flexible. Forms validation provides good support for user-based authentication authorizations, which can authenticate users through a login page, send the user's identity back to the client's cookie, and then access the Web application with this identity cookie to the server. The authorization settings on the server can be controlled according to the access authorization of different users in different directories. The problem is that in practice we often need to be role-based, or based on user group authentication and authorization. For a website, the general mode of authentication authorization should be: according to the actual needs of the user into different identities, is the role, or the user group, the verification process not only to verify the identity of the user itself, but also to verify that it belongs to which role. Access authorization is set by role, which resources are accessible to some roles, which resources are not accessible, and so on. If the user to authorize access will be a very impractical approach, there are many users, but also may be at any time increase or decrease, it is not possible in the configuration file for the increasing number of new users to add access authorization. Here's a look at the process of forms. Forms authentication Rationale: One authentication To use Forms authentication, first make the appropriate settings in the Web.config in the application root directory: <authentication mode= "Forms" > <forms name= ". Aspxauth "loginurl="/login.aspx "timeout=" path= "/" > </forms> </authentication> where <authentication mode= "forms" > means that this application uses forms validation. 1. The name in the <forms> label specifies the HTTP Cookie to use for authentication. By default, the value of name is. Aspxauth. After authenticating the user in this way, a FormsAuthenticationTicket type of authentication ticket is established with the user's information, and then encrypted into a string, Finally, the string is written to the cookie of the client's name-specified name. Once this cookie is written to the client, the user who accesses the Web application again will send it along with the cookie to the server, and the server will know that the user is authenticated. If you look at the information that the authentication ticket contains, let's take a look at the FormsAuthenticationTicket class: cookiepath: Returns the path where the Cookie is issued. Notice that the path to the form is set to/. Because forms are case-sensitive, this is a protective measure to prevent the case of URLs in a site that are not case-sensitive. This is used when refreshing cookies Expiration: Gets the date/time when the Cookie expires. ispersistenT: Returns True if a persistent Cookie has been issued. Otherwise, the authentication Cookie is limited to the browser life cycle scope. issuedate: Gets the date/time when the Cookie was originally issued. name: Gets the user name associated with the authentication Cookie. UserData : Gets the application definition string stored in the Cookie. version: Returns the byte version number for future use. 2. The loginurl in the <forms> label specifies the URL to redirect the request to if no valid authentication Cookie is found. The default value is default.aspx. Loginurl specified page is used to authenticate the user, generally this page provides user input user name and password, the user submitted by the program to their own needs to verify the legality of the user (most of the situation is the user input information in the database with the user table to compare), if the validation of the user is valid, Generates an authentication ticket that corresponds to this user, writes to the client's cookie, and finally redirects the browser to the page that was requested by the user at the initial initial request. Typically, the FormsAuthentication.RedirectFromLoginPage method is used to generate the authentication ticket, Write back to the client, browser redirection, and so on a series of actions.
public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strcookiepath);
which UserName: This is the user's logo, which is used to mark the unique designation of this user, and does not necessarily map to the user account name. createPersistentCookie: Indicates whether a persistent Cookie is issued. If it is not a persistent cookie, The validity of a cookie expiration property has the current time plus web.config in the timeout time, each request page, in the authentication process, will determine whether the expiration of half, if the words update the validity of a cookie; if lasting cookie,expiratio n property is meaningless, when the validity of the authentication ticket has the expires decision of the cookie, the RedirectFromLoginPage method gives the expires attribute the 50-year validity period. strCookiePath: Identifies the path to write the generated cookie to the client, which is saved in the authentication ticket when the authentication ticket cookie is refreshed (this is also the path that generated the cookie), and if there is no strCookiePath parameter, use the web.config The settings for the Path property.
As you can see here, there are only three parameters for this method, and there are seven properties for the authentication ticket, and the insufficient four parameters are as follows: IssueDate: The cookie issue time is drawn from the current time, Expiration: The expiration time is calculated from the current time and the timeout parameter in the <forms> label below. This parameter is meaningful for non-persistent cookies. UserData:This property can be written to some user-defined data by the application, this method does not use this attribute, but simply place this property as an empty string, note this property, which we will use later. Version:The version number is provided automatically by the system.
After the RedirectFromLoginPage method generates the generated authentication ticket, it invokes the Formsauthentication.encrypt method, encrypting the authentication ticket as a string, which will be the string. Aspxauth is the value of a cookie for the name. The other attributes of this cookie are generated: The Domain,path property is a true value, expires depending on the createPersistentCookie parameter, if the persistent cookie,expires is set to expire after 50; if it is not a persistent cookie, The Expires property is not set. After the authentication cookie is generated, the cookie is added to the response.cookies, waiting to be sent to the client. Finally, the RedirectFromLoginPage method calls the Formsauthentication.getredirecturl method to obtain the page that the user originally requested and redirects to this page.
3. The <forms> tab in timeout and path is provided with authentication tickets written to cookie expiration and default path. This is the process based on forms authentication that completes the identification of the user. The following describes access authorization based on forms authentication. Second Access authorization Authenticated identity, is to use this identity, according to different identities we can do different operations, processing, the most common is to different identities for different authorization, forms validation provides such a function. Forms authorization is directory based, and you can set access permissions for a directory, such that users can access the directory, and those users cannot access it. Similarly, authorization settings are set in the Web.config file in the directory you want to control: <AUTHORIZATION> <allow users= "comma-separated List of users" roles= comma-separated List of roles " verbs=" comma-separated List of Verbs "/> <deny users=" comma-separated List of users roles= "comma-separated List of roles" verbs= "comma-separated List of Verbs"/> </authorization> <allow> label indicates permission to access, where the properties 1. Users: A comma-delimited list of user names that have been granted access to resources. The question mark (?) allows anonymous users, and an asterisk (*) allows all users. 2. Roles: A comma-delimited list of roles that have been granted access to resources. 3. Verbs: A comma-delimited list of HTTP transport methods that have been granted access to resources. The verbs registered to asp.net are, POST, and DEBUG. The <deny> label indicates that access is not allowed. Where the attributes are the same as above. At run time, the authorization module iterates through the <allow> and <deny> tags until it finds the first access rule for a particular user. It then allows or denies access to the URL resource based on whether the first access rule found is <allow> or <deny> rules. The default authentication rule in the Machine.config file is <allow users= "*"/>, so access is allowed by default unless otherwise configured. So how do these user and roles get it? Let's look at the details of the authorization process: 1. Once a user visits the website, the identity of the line login is confirmed, and the cookie of the authentication ticket is also written to the client. The user then requests the Web page again, and the authentication ticket cookie is sent to the server. On the service side, asp.net assigns a HttpApplication object to each HTTP request to handle the request, and after the Httpapplication.authenticaterequest event, the security module has established a user identity, that is, the identity of the user has been established on the web side, which Identity is entirely created by the cookie that the client sends back the authentication ticket. 2. User identity in the HttpContext.User attribute, the page can be page.context to get the HttpContext object associated with this page. For forms validation, the HttpContext.User property is an GenericPrincipal type object, GenericPrincipal has only one public property identity, a private m_role attribute, is string[] Type, which contains an array of roles that this user belongs to, and a public method IsInRole (string role) to determine whether the user belongs to a persona. Because the role is not provided in the cookie for the authentication ticket, which means that the forms authentication ticket does not provide the user's role information, for forms authentication, the m_ of the GenericPrincipal user object that is obtained at the server The role attribute is always empty. 3. GenericPrincipal. The Identity property is an object of type formsidentity, which has a name attribute, which is the user's indication that the access authorization authenticates this property as user. FormsIdentity also has a property that is the Ticket property, which is the authentication ticket FormsAuthenticationTicket type, which is the authentication ticket that the server wrote to the client before. After the server obtains the authentication ticket FormsAuthenticationTicket object, see if the authentication ticket is not a persistent authentication. Yes, to update the cookie for this authentication ticket based on the validity period set by the Timeout property in Web.config (to avoid compromising performance, update the cookie after more than half the specified time). This can result in a loss of accuracy. Persistent cookies do not timeout. ) 4. Prior to the Httpapplication.resolverequestcache event, ASP.net started to obtain the user-requested page and set up HttpHandler control points. This means that when the Httpapplication.resolverequestcache event is authenticated to the user's access rights, and the user or role has permission to access the page, then it is meaningless to change the user's identity or role in the lifetime of the request. This is the entire process of forms validation, as you can see that this forms validation is based on the user and does not provide direct support for role validation. The name attribute in the authentication ticket formsauthenticationticket is user-marked, and there is actually a property userdata, which can be written by the application to write some custom data that we can use to store the role information. So as to achieve the purpose of role-based verification. Forms Authentication Role-based Authorization One authentication The setting of the <authentication> in Web.config is the same: <authentication mode= "Forms" > <forms name= ". Aspxauth "loginurl="/login.aspx "timeout=" path= "/" > </forms> </authentication> /login.aspx validate the user's legality page, after verifying the legality of the user, there is also a process to obtain what role this user belongs to, this look at how each application itself is designed, generally in the database will have a use_role table, It is possible to derive from the database what role this user belongs to, not to delve into how to get the user's role, and finally to be able to get all of the role of this user corresponding to a comma-delimited string. In the above non role-based approach, we used the FormsAuthentication.RedirectFromLoginPage method to complete the generation of authentication tickets, write back to the client, browser redirection and so on a series of actions. This method uses some definite settings to complete a series of actions, in role-based validation we can not use this method to implement, to do step-by-step, to add some custom settings in: 1. First, create an authentication ticket based on the user's ID, and the character string that the user belongs to. Public FormsAuthenticationTicket ( int version, //set to 1 String name, //user label DateTime issuedate, //cookie The time of issue, set to DateTime.Now DateTime expiration, //Expiration Time BOOL Ispersistent, //whether persistent (set as required, if set to persistent, in the issue of Cookies, the cookie's expires settings must be set) String userData, //Here is a comma-separated role string with the above prepared String Cookiepath //set to "/", which is consistent with the path that issued the cookie because the cookie is refreshed To use this path ); FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1, "Kent", DateTime.Now, DateTime.Now.AddMinutes (30) , False,userroles, "/"); 2. Cookies that generate the authentication ticket 2.1 The authentication ticket encryption sequence into a string String hashticket = Formsauthentication.encrypt (Ticket); 2.2 Generating cookies HttpCookie Usercookie = new HttpCookie (Formsauthentication.formscookiename, Hashticket); Formsauthentication.formscookiename is used to get the name of the authentication cookie set in Web.config, by default. Aspxauth ". If the Ispersistent property in the authentication ticket is set to a persistent class, the Expires property of the cookie must be set so that the cookie is saved to the client's cookie file as a persistent cookie. 3. Export the authentication ticket cookie to the client The authentication ticket cookie is appended to the output cookie collection by Response.Cookies.Add (Usercookie) and sent to the client. 4. Redirect to the initial page of the user's application. Verify part of the code (this part of the code is clicked on the Login button event handling code on the Login.aspx page): private void Buttonlogin_click (object sender, System.EventArgs e) { string user = Textboxuser.text;//Read user name string password = Textboxpassword.text;//Read password if (Confirm (user,password) = = True)The//confirm method is used to verify the legality of the user { String userroles = usertorole (user);//Call the Usertorole method to get the role string FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1,user,datetime.now, DateTime.Now.AddMinutes (30 ), False,userroles, "/");//Establish an authentication ticket object String hashticket = Formsauthentication.encrypt (Ticket);//Encrypt serialization verification ticket as String HttpCookie Usercookie = new HttpCookie (Formsauthentication.formscookiename, Hashticket); //Generate Cookies CONTEXT.RESPONSE.COOKIES.ADD (Usercookie);//Output Cookie Context.Response.Redirect (context.request["ReturnUrl"]);//Redirect to initial page of user request } Else { //user identity is not confirmed when the code } } //This method is used to verify the legality of the user private bool Confirm (string user,string password) { //The corresponding code } //This method is used to obtain all the role of the user corresponding to a comma-separated string private string Usertorole (string user) { //The corresponding code } Two role-based access authorization What we're going to do here is to restore the message of the representation role saved in UserData in the client's saved authentication ticket to the GenericPrincipal object that represents the user's identity on the server (remember, in the original validation process, The GenericPrincipal object contains only user information and does not contain role information. In the process of an HTTP request, the Httpapplication.authenticaterequest event indicates that the security module has established a user identity, that is, the identity of the user has been established on the web side, after which we can obtain user identity information. Before the Httpapplication.resolverequestcache event, ASP.net started to get the user's requested page and set up HttpHandler control points, and then the user's permissions were validated. So the work of restoring the user role can only be done in the process between the Httpapplication.authenticaterequest event and the Httpapplication.resolverequestcache event. We chose to do this in the Application_authorizerequest event, and we can handle all the HttpApplication events in the Global.asax file as follows: protected void Application_authorizerequest (object sender, System.EventArgs e) { HttpApplication App = (HttpApplication) sender; HttpContext Ctx = App.context;//Get the HttpContext object associated with this HTTP request if (Ctx.Request.IsAuthenticated = = True)//authenticated user for role processing { FormsIdentity Id = (formsidentity) Ctx.User.Identity; FormsAuthenticationTicket Ticket = Id.ticket;//Obtain an authentication ticket string[] Roles = Ticket.UserData.Split (', ');//Convert role data in the authentication ticket to an array of strings Ctx.user = new GenericPrincipal (Id, Roles);//Add the original identity and role information create a new GenericPrincipal to represent the current user, so that the current user has roles information } } Visitors have both user and role information to control the user's access rights by using role in Web.config. |