The most used and most flexible.
Forms authentication provides good support for user-based authentication and authorization, which can be verified on a login page.
User identity, send the user's identity back to the client's Cookie, then the user can access this web application again
Will be sent to the server together with this identity Cookie. The authorization settings on the server can be set according to different directories
Same as the user's access authorization.
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: Divide users into different ones based on actual needs
The identity is the role or user group. The authentication process not only verifies the identity of the user, but also verifies the identity of the user.
Verify which role it belongs. Access authorization is set based on the role. which resources can some roles access,
Resources cannot be accessed. It would be very impractical to authorize access based on users.
And can 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, name
The value is. ASPXAUTH. This method is used to verify the user and create
FormsAuthenticationTicket type authentication ticket, then encrypt and serialize it into a string, and finally
The string is written to the Cookie with the name specified by the client name. Once the Cookie is written to the client, the user again
When you access this web application, it will be sent together with the Cookie to the server, and the server will know that this 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 /. Due to form Differentiation
This is a protective measure to prevent URL inconsistencies. This is refreshing
Cookie
Expiration: the date/time when the Cookie expires.
IsPersistent: returns true if a persistent Cookie has been sent. Otherwise, the authentication Cookie
The browser lifecycle will be limited.
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
The URL to which the request is redirected. The default value is default. aspx. The page specified by loginUrl is used for verification.
User identity, generally This page provides the user to enter the user name and password, after the user is submitted, the program will come according to their own needs
Verify the legality of the user (in most cases, the user input information is compared with the user table in the database ).
If the user is valid, the authentication ticket corresponding to the user is generated, written to the Cookie of the client, and the browser is redirected.
To the page of the user's initial request, the FormsAuthentication. RedirectFromLoginPage method is generally used.
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 time in web. config.
Timeout time, each request page, in the authentication process, will determine whether half of the validity period has passed,
If yes, update the cookie validity period. If the cookie is persistent, the Expiration attribute is meaningless.
The validity period of the verification ticket is determined by the Expires of the cookie. The RedirectFromLoginPage method is used to set the Expires attribute.
The validity period is 50 years.
StrCookiePath: indicates the path to write the generated Cookie to the client. This path is saved in the authentication ticket.
The Path is used to refresh the authentication ticket Cookie (this is also the Path for generating the Cookie). If no
Use the path attribute settings in web. config.
We can see that there are only three parameters in this method, and there are seven attributes of the identity authentication ticket. The four parameters below are:
Come on:
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
The number is meaningful to non-persistent cookies.
UserData: This attribute can be used to write user-defined data to the application.
Property, but simply set this property to a null string. Please note that this property will be used later.
Version: the Version number is automatically provided by the system.
After the RedirectFromLoginPage method is used to generate an authentication ticket
FormsAuthentication. Encrypt method to Encrypt the authentication ticket as a string, which will be
. ASPXAUTH is the name of a Cookie value. Generation of other attributes of this Cookie: Domain, Path attribute
Expires depends on the createPersistentCookie parameter. If it is a persistent cookie, Expires is set
Expired 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 is called to obtain the FormsAuthentication. GetRedirectUrl method.
Go to the page requested by the user and redirect to this page.
3. the timeout and path in the <forms> label provide the authentication ticket write to Cookie expiration time and default
Path.
The above process is based on Forms authentication, which completes the confirmation of user identity. The following describes Forms-based
Authentication Access authorization.
2. Access Authorization
This identity is used for authentication. We can perform different operations and processes based on different identities,
The most common thing is to authorize different identities. Forms authentication provides this function. Forms authorization is
Directory-based access permissions can be set for a directory. For example, these users can access this directory
Some 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 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 target user
The first access rule. Then, it determines whether the first access rule is <allow> or <deny>.
Allow or deny access to URL resources. 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 can log on to confirm his identity, and the cookie of the authentication ticket is also written
Client. After the user applies for the web page again, the cookie of the authentication ticket will be sent to the service
. On the server side, asp.net assigns an HttpApplication object for each http request to process this request.
After the HttpApplication. AuthenticateRequest event, the security module has created a user ID, which is
The identity of this user has been established on the web end, and this identity is completely the identity verification ticket sent back by the client
Cookie.
2. the User identity is in the HttpContext. User attribute. On the Page, you can use Page. Context to obtain the same
HttpContext object related to this page. For Forms authentication, the HttpContext. User attribute is
GenericPrincipal type object. GenericPrincipal has only one public attribute Identity, which has a private
Some m_role attributes are of the string [] type, which stores the role arrays of this user, and 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 have
Provide the role information of this user. Therefore, for Forms authentication, the GenericPrincipal user obtained on the server end
The m_role attribute of the object is always empty.
3. The GenericPrincipal. Identity attribute is a FormsIdentity type object, which has
Name attribute, which is the identifier of the user. Access Authorization uses this attribute as the user for authorization verification.
FormsIdentity also has a Ticket attribute, which is an identity authentication Ticket
The FormsAuthenticationTicket type is the authentication ticket that the server has previously written to the client.
After obtaining the authentication ticket FormsAuthenticationTicket object, the server can view the authentication ticket
Whether it is non-persistent authentication. If yes, it must be updated based on the validity period set by the timeout attribute in web. config.
Cookie of this authentication ticket (to avoid compromising performance, update the ticket after more than half of the specified time
Cookie. This may cause a loss of accuracy. Persistent Cookie does not time out .)
4. Before the HttpApplication. ResolveRequestCache event, asp.net began to obtain
Page to create an HttpHandler control point. This means that in HttpApplication. ResolveRequestCache
The 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 request lifecycle.
The above is the entire process of Forms verification. It can be seen that this Forms verification is based on the user, not for role Verification
Certificates provide direct support. The Name attribute in the authentication ticket FormsAuthenticationTicket is the user ID.
There is also an attribute UserData, which can be written to custom data by the application. We can
This field is used 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. aspx verify the validity of the user page, after verifying the legality of the user, you need to obtain the user
Which role processes are involved? This depends on how each application is designed. Generally, there is
Use_role table, which of the following roles can be obtained from the database?
Finally, all the role corresponding to this user can be obtained using a comma to separate a string.
In the above non-role-based method, we used
FormsAuthentication. RedirectFromLoginPage method to generate an authentication ticket and write it back to the client,
Browser redirection and other actions. In this method, a series of actions will be completed with some accurate settings.
In role verification, we cannot use this method. We need to do it step by step to add some custom settings.
Come:
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 authentication set in web. config.
Cookie name. The default value is ". ASPXAUTH ".
If the isPersistent attribute in the authentication ticket is set to a persistent class, the Expires attribute of this cookie must be
So that the cookie is 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.
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
ID verification ticket object
String HashTicket = FormsAuthentication. Encrypt (Ticket); // encryption serialization Verification
The 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 user
Initial Application page
}
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
Here, we need to restore the role information stored in UserData in the authentication ticket saved by the client.
Repeat to the GenericPrincipal object on the server that represents the user identity (remember, during the original verification process,
The GenericPrincipal object only contains user information, but does not contain role information)
During an Http request, the HttpApplication. AuthenticateRequest event indicates that the security module has been created
Establish a user identity, that is, the identity of this user has been established on the web end. After this event, we can obtain
User identity information.
Before the HttpApplication. ResolveRequestCache event, asp.net starts to retrieve the user request page.
The HttpHandler control point is created, and the user's permissions must be verified.
In the HttpApplication. AuthenticateRequest event and
During the process between HttpApplication. ResolveRequestCache events.
We select Application_AuthorizeRequest event to do this, which can be 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 authentication Ticket
String Array
Ctx. User = new GenericPrincipal (Id, Roles); // Add the original Identity to the role
GenericPrincipal indicates 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 user access.
The permission is queried.