Role verification authorization based on Forms verification in ASP.NET

xiaoxiao2021-03-06  97

The default is Default.aspx. LoginURL specified by the page is used to verify the user's identity. Generally, this page provides users enter the username and password. After the user is submitted, the user's legitimacy is verified according to its own needs (most cases, enter the user into the database with the database. The user table is compared.) Generate a series of actions such as authentication ticket, write back to client, browser redirection, etc.public static void RedirectFromLoginPage (String UserName, Bool CreatePersister (String StrCookiePath); where: username: is the sign of this user, used to mark this user The only sign is not necessarily mapped to the user account name .CreatePersisterCookie: The label is launched for a long-lasting cookie. If you are not a lasting cookie, the Validity period of the cookie has the current time plus the timeout of the timeout. When each request page, during the verification, it will determine whether the validity is half, if you update a cookie Validity period; if it is a lasting cookie, the expression attribute is meaningless. At this time, the validity period of the authentication ticket has a cookie's Expires decision, and the RedirectFromLoginPage method is set to the Expires property of the 50-year validity period. StrCookiePath: Marking the path to the client to the client, saving this path in the authentication ticket is used when refreshing authentication ticket cookies (this is also generated cookie's Path), if there is no strcookiepath parameter, use Web.config The setting of the Path property. It can be seen here that this method parameter is only three, and the attributes of authentication tickets have seven, and the four parameters of the insufficient are: Issuedate: cookie issued by the current time, expiration: expiration time by the current time And the Timeout parameter is calculated in the tag that you want to say. This parameter makes sense to non-persistent cookies. UserData: This property can be written to some user-defined data. This method is not used in this property, just simply set this property as an empty string, please note this property, after we will use this property. Version: The version number is automatically provided by the system .RedirectFromLoginPage method After generating an authentication ticket, the FormSauthentication.Encrypt method is called, and the authentication ticket is encrypted as a string. This string will be the value of a cookie named by .aspxauth. . The generation of this cookie's other properties: domain, the Path property is the value of the Value, and the Expires will depend on the cretePersistentCookie parameter. If the lasting cookie, Expires set to 50 years later; if it is not a lasting cookie, the Expires property is not set. After generating authentication cookies, add this cookie to response.cookies and wait to send to the client. Final RedirectFromLoginPage method calls the FormSauthentication.getredirectURL method to get the page of the user's original request, redirect to this page. 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 access authorization verify the identity, is to use this identity, according to different identities, we can do different operations, processing, the most common is to separate 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: Tags represent allow access, where properties 1. Users: A comma-separated user name list, which has been granted access to resources. Question mark (?) Allows an anonymous user; as an asterisk (*) allows all users. 2. Roles: A comma-separated list of roles that have been granted access to resources. 3. VERBS: A comma-separated HTTP transmission method list, which has been granted access to resources. The predicates for registration to ASP.NET are GET, HEAD, POST, and DEBUG. The tag indicates that you are not allowed. The properties are the same. At runtime, the authorization module iterates through and tag until it finds the first access rule that is suitable for specific users. Then, it allows or reject access to the URL resource based on the first access rule found to be or rules. The default authentication rules in the Machine.config file are , so access is allowed by default unless otherwise configures. 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, login to confirm the identity, 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 in Web.config's The setting or the same: /login.aspx Verify that the user's legitimacy page, after verifying the user's legitimacy, there must be a process of which the user belongs to which Role belongs, this See how each application itself is designed, usually there is a use_role table in the database, which role can be obtained from the database, and how to get the user's corresponding role, and finally it will definitely be able to get The user corresponds to all the ROLE segmented with a comma. In the above non-role method, we use the Formsauthentication.RedirectFromLoginPage method to complete a series of actions such as generating authentication tickets, write back to clients, browser redirection.

This method uses some of the provincial settings to complete a series of actions. In role-based verification, we cannot use this method to implement, to step by step, so that some custom settings are added: 1. First Create an authentication ticket PUBLIC FORMSAUTHENTICTICKET (int version, // set to 1String name, //), set to datetime.now datetime, based on user marking strings Expiration, // Expired time BOOL ISPERSISTENT, / / ​​Whether it is persistence (setting as needed, if it is set to persistence, when emitting cookies, cookie's Expires setting must be set) String UserData, // Here is ready for use. The comma-divided role string string cookiepath / / set to "/", this is the same as 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. Cookie2.1 generating authentication tickets into a string String Hashticket = FormSauthentication.encrypt (Ticket); 2.2 Generation cookieHttpCookie userCookie = new HttpCookie (FormsAuthentication.FormsCookieName, HashTicket);. FormsAuthentication.FormsCookieName is used to obtain the name of the authentication cookie web.config set, the default is ".ASPXAUTH" If isPersistent property is set in the authentication ticket is Helder, this cookie's Expires property must be set so that this cookie is used as a cookie file that lasts for lasting cookies. 3. 3. Output authentication ticket cookies to the client via response.cookies.add (usercooki e) Add the authentication ticket cookie to the output cookie collection, send it to the client. 4. Redirect to the user application's initial test page. Verify partial code (this part of the code is on the login.aspx page Click the login button on the login.aspx page 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 method To verify {string userroles = useerTorole (user) of user legitimacy; // calls the Usertorole method to get the Role string FormsauthenticationalTicket Ticket = New FormsauthenticationalTicket (1, user, datetime.now, datetime. Now.addminutes (30), False, Userroles, "/"); // Establish an authentication ticket object string hashticket = forMsauthentication.encrypt (ticket);

转载请注明原文地址:https://www.9cbs.com/read-123617.html

New Post(0)