There are three authentication methods for Asp. Net: "Windows | Forms | Passport", among which Forms authentication 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 obtains the user request page and establishes 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. 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.