There are three authentication methods for Asp.net: "Windows | forms | passport", among which forms is the most used and most flexible.
Forms authentication provides good support for user authentication and authorization. You can use a login page to verify the user's identity and send the user's identity back to the client's cookie, then the user accesses the web application and sends it to the server together with the identity cookie. The authorization settings on the server can control the access authorization of different users according to different directories.
The problem arises. In practice, what we often need is role-based or user group-based authentication and authorization. For a website, the general authentication and authorization mode should be like this: users are divided into different identities based on actual needs, namely roles, or user groups, the authentication process not only verifies the identity of the user, but also verifies the role it belongs. Access authorization is based on roles. Some roles can access resources and resources. It would be a very impractical practice to authorize access based on users. There are many users, which may be increased or decreased at any time, it is impossible to add access authorization to new users at any time in the configuration file.
The following describes the forms process.
Basic Principles of Forms authentication:
1. Authentication
To use forms authentication, you must first make the corresponding settings in Web. config in the application root directory:
<Authentication mode = "forms">
<Forms name = ". aspxauth" loginurl = "/login. aspx" timeout = "30" Path = "/">
</Forms>
</Authentication>
<Authentication mode = "forms"> indicates that the application adopts Forms authentication.
1. Name in the <forms> label indicates the HTTP cookie to be used for identity authentication. By default, the value of name is. aspxauth. After the user is verified in this way, a formsauthenticationticket authentication ticket is created based on the user information, and then encrypted and serialized into a string, finally, write the string to the cookie with the name specified by the client name. once the cookie is written to the client, the user will be sent to the server together with the cookie when accessing the web application again, and the server will know that the user has been verified.
Let's take a look at the information contained in the identity authentication ticket. Let's take a look at the formsauthenticationticket class:
Cookiepath: return the cookie sending path. Note: the path of the form is set /. The form is case-sensitive, which is a protection measure to prevent the URL in the site from being case-insensitive. This is used when refreshing cookies.
Expiration: the date/time when the cookie expires.
Ispersistent: returns true if a persistent Cookie has been sent. Otherwise, the authentication cookie is restricted within the browser lifecycle.
Issuedate: Get the date/time when the cookie was originally sent.
Name: gets the username associated with the authentication cookie.
Userdata: Get 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 that if no valid authentication cookie is found, it is the URL to which the login redirects the request. The default value is default. aspx. The page specified by loginurl is used to verify the user's identity. Generally, this page provides the user's user name and password, after the user submits the request, the program verifies the validity of the user based on his/her own needs (in most cases, the user input information is compared with the user table in the database). If the user is verified to be valid, generate the authentication ticket corresponding to this user, write it to the cookie of the client, and redirect the browser to the page of the user's initial request. generally, formsauthentication is used. the redirectfromloginpage method is used to generate an authentication ticket, write it back to the client, and redirect the browser.
Public static void redirectfromloginpage (string username, bool createpersistentcookie, string strcookiepath );
Where:
Username: indicates the unique identifier of the user. It does not have to be mapped to the user account name.
Createpersistentcookie: Indicates whether a persistent cookie is sent.
If it is not a persistent cookie, the expiration attribute of the cookie's validity period includes the current time plus the web. the timeout time in config. When each request is sent to the page, the system checks whether half of the validity period has been passed during identity authentication. If so, the cookie validity period is updated. If it is a persistent cookie, the expiration attribute is meaningless. The validity period of the authentication ticket is determined by the cookie expires. The redirectfromloginpage method sets the validity period of the expires attribute to 50 years.
Strcookiepath: indicates the path to write the generated cookie to the client. The path saved in the authentication ticket is used when the authentication ticket cookie is refreshed (this is also the path for generating the cookie ), if the strcookiepath parameter is not specified, the web. set the path attribute in config.
We can see that there are only three parameters in this method, and there are seven attributes of the identity authentication ticket. The following are the four parameters:
Issuedate: the cookie sending time is obtained from the current time,
Expiration: The expiration time is calculated by the current time and the timeout parameter in the <forms> label to be mentioned below. This parameter is valid for non-persistent cookies.
Userdata: This attribute can be used to write some user-defined data. This attribute is not used in this method, but it is simply set to a null string. Please note this attribute, this attribute will be used later.
Version: the version number is automatically provided by the system.
After the redirectfromloginpage method generates an authentication ticket, it will call the formsauthentication. Encrypt method to encrypt the authentication ticket as a string, which will be a cookie value named by. aspxauth. Other attributes of this cookie are generated: domain. The path attribute is a saved value. expires depends on the createpersistentcookie parameter. If it is a persistent cookie, expires after 50 years; if the cookie is not persistent, The expires attribute is not set.
After an authentication cookie is generated, add the cookie to response. Cookies and wait for the cookie to be sent to the client.
Finally, the redirectfromloginpage method calls the formsauthentication. getredirecturl method to obtain the page requested by the user and redirect it to this page.
3. the timeout and path in the <forms> label provide the authentication ticket write to the cookie expiration time and default path.
The above process is based on Forms authentication, which completes the confirmation of user identity. The following describes Access authorization based on Forms authentication.
2. Access Authorization
If you verify your identity, you must use this identity. You can perform different operations and processes based on different identities. The most common thing is to authorize different identities, forms authentication provides such a function. Forms authorization is based on directories. You can set access permissions for a directory. For example, these users can access this directory, and those users cannot access this directory.
Similarly, the authorization settings are set in the web. config file under 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> the label indicates that access is allowed, and Its Attributes
1. Users: A comma-separated list of user names that have been granted access to resources. Question mark (?) Anonymous Users are allowed. asterisks (*) Allow all users.
2. Roles: A comma-separated list of roles that have been granted access to resources.
3. verbs: A comma-separated list of HTTP transfer methods that have been granted access to resources. The predicates registered with ASP. NET are get, Head, post, and debug.
<Deny> the tag indicates that access is not allowed. The attributes are the same as above.
At runtime, the authorization module iterates through <allow> and <deny> until it finds the first access rule suitable for a specific user. Then, it allows or denies access to URL resources based on the first access rule found: <allow> or <deny>. The default authentication rule in the machine. config file is <allow users = "*"/>. Therefore, access is allowed by default unless otherwise configured.
So how can these users and roles be obtained? The detailed authorization process is as follows:
1. Once a user accesses this website, he or she can log on and confirm his or her identity. The cookie of the authentication ticket is also written to the client. Then, the user applies for the web page again, and the cookie of the authentication ticket will be sent to the server. On the server side, Asp.net assigns an httpapplication object for each HTTP request to process the request. after the authenticaterequest event, the security module has established a user identity, that is, the identity of this user has been established on the Web end, and this identity is completely created by the cookie of the authentication ticket sent by the client.
2. the user identity is in the httpcontext. User attribute. On the page, you can use page. Context to obtain the httpcontext object related to the page. For forms verification, httpcontext. the user attribute is a genericprincipal type object. genericprincipal has only one public attribute identity, which has a private m_role attribute, which is of the string [] type and stores the array of role to which the user belongs, there is also a public method isinrole (string role) to determine whether the user belongs to a role.
Because the role attribute is not provided in the cookie of the authentication ticket, that is, the forms authentication ticket does not provide the role information of this user, for Forms authentication, the m_role attribute of the genericprincipal user object obtained on the server is always empty.
3. The genericprincipal. Identity attribute is a formsidentity type object. This object has a name attribute, which indicates the user. Access Authorization uses this attribute as the user for authorization verification. Formsidentity also has a ticket attribute, which is the formsauthenticationticket type of authentication ticket, that is, the authentication ticket that the server previously wrote to the client.
After obtaining the authentication ticket formsauthenticationticket object, the server checks whether the authentication ticket is non-persistent authentication. the timeout attribute set in config is valid to update the cookie of the authentication ticket (to avoid compromising performance, the cookie is updated after more than half of the specified time. This may cause a loss of accuracy. Persistent cookie does not time out .)
4. Before the httpapplication. resolverequestcache event, Asp.net starts to obtain the user request page and establish the httphandler control point. This means that in httpapplication. the resolverequestcache event verifies the user's access permissions to check whether the user or role has the permission to access this page, it makes no sense to change the identity or role of the user within the lifecycle of the request.
The above is the entire process of forms verification. It can be seen that this forms verification is based on the user and does not provide direct support for role verification. The name attribute in the authentication ticket formsauthenticationticket is the user ID. In fact, there is also the userdata attribute, which can be written to custom data by the application, we can use this field to store role information for role-based authentication.
Forms authentication role-based authorization
1. Authentication
The <authentication> Settings in Web. config are the same:
<Authentication mode = "forms">
<Forms name = ". aspxauth" loginurl = "/login. aspx" timeout = "30" Path = "/">
</Forms>
</Authentication>
/Login. on the aspx user legality verification page, after verifying the legality of the user, there is also a process for obtaining the role of the user. This depends on how the applications are designed, generally, there is a use_role table in the database, which can be obtained from the database which role this user belongs to. We will not go into detail how to obtain the role corresponding to the user, finally, all the role corresponding to this user can be obtained using a comma to separate a string.
In the preceding non-role-based method, the formsauthentication. redirectfromloginpage method is used to generate an authentication ticket, write it back to the client, and redirect the browser. This method will complete a series of actions with some real-time settings. In role-based verification, we cannot use this method for implementation. It should be done step by step, to add custom settings:
1. Create an authentication ticket based on the user ID and the character string of the user's role.
Public formsauthenticationticket (
Int version, // set to 1
String name, // user ID
Datetime issuedate, // cookie sending time, set to datetime. Now
Datetime expiration, // expiration time
Bool ispersistent, // whether it is persistent (set as needed. If it is set to persistent
Cookie expires must be set)
String userdata, // The role string prepared above that is separated by commas (,).
String cookiepath // set to "/", which must be the same as the cookie sending path, because the cookie is refreshed
Use this path
);
Formsauthenticationticket ticket = new formsauthenticationticket (1, "Kent", datetime. Now, datetime. Now. addminutes (30), false, userroles ,"/");
2. Generate a cookie for the authentication ticket
2.1 serialize the authentication ticket into a string
String hashticket = formsauthentication. Encrypt (ticket );
2.2 generate cookie
Httpcookie usercookie = new httpcookie (formsauthentication. formscookiename, hashticket );
Formsauthentication. formscookiename is used to obtain the name of the authentication Cookie set in Web. config. The default value is ". aspxauth ".
If the ispersistent attribute in the authentication ticket is set to a persistent class, the expires attribute of the cookie must be set so that the cookie will be saved as a persistent cookie in the cookie file of the client.
3. output the authentication ticket cookie to the client
Use response. Cookies. Add (usercookie) to append the authentication ticket cookie to the output Cookie set and send it to the client.
4. Redirect to the user's initial trial page.
Verify some code (this code is the event processing code by clicking the logon button on the login. ASPX page ):
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) // The confirm method is used to verify the validity of the user
{
String userroles = usertorole (User); // call the usertorole method to obtain the role string
Formsauthenticationticket ticket = new formsauthenticationticket (1, user, datetime. Now, datetime. Now. addminutes (30), false, userroles, "/"); // create an authentication ticket object
String hashticket = formsauthentication. Encrypt (ticket); // The encrypted serialization validation ticket is a string
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 of the user application
}
Else
{
// Code for unconfirmed user identity
}
}
// This method is used to verify the validity of the user
Private bool confirm (string user, string password)
{
// Corresponding code
}
// This method is used to obtain a comma-separated string for all the role corresponding to the user
Private string usertorole (string user)
{
// Corresponding code
}
2. Role-Based Access Authorization
What we need to do here is to restore the role information saved in userdata in the authentication ticket saved by the client to the genericprincipal object on the server that represents the user's identity (Remember, in the original verification process, the genericprincipal object only contains user information, but does not contain role information)
Httpapplication. the authenticaterequest event indicates that the security module has established a user identity, that is, the identity of this user has been established on the Web end. After this event, we can obtain the user identity information.
In httpapplication. before the resolverequestcache event, Asp.net began to obtain the page of the user request and set up the httphandler control point. Then, the user's permissions must be verified. authenticaterequest event and httpapplication. during resolverequestcache events.
We select application_authorizerequest to do this. We can process 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; // obtain the httpcontext object related to this HTTP Request
If (CTX. Request. isauthenticated = true) // users who have verified the role can process the role.
{
Formsidentity id = (formsidentity) CTX. User. identity;
Formsauthenticationticket ticket = ID. Ticket; // get the authentication ticket
String [] roles = ticket. userdata. Split (','); // convert the role data in the ticket to a String Array
CTX. User = new genericprincipal (ID, roles); // Add the original identity with the role information to create a genericprincipal to indicate the current user, so that the current user has the role information
}
}
When a visitor has both user and role information, he can use role in Web. config to control the user's access permissions.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/Python/archive/2008/11/11/3277366.aspx