In Asp.net, role-based forms authentication is used, which goes through several steps:
1. Configure the system web. config
< System . Web >
< Authentication Mode = "Forms" >
< Forms Name = ". Yaocookies" Loginurl = "/Duan/manage/login. aspx" Protection = "All"
Timeout = "20" Path = "/" />
</ Authentication >
</ System. Web >
<Authentication mode = "forms"> indicates the applicationProgramUse Forms authentication.
1). the 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.
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> tag. 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.
Generation of other attributes of this cookie:
Domain and path attributes are saved values. expires depends on the createpersistentcookie parameter. If the cookie is persistent, expires after 50 years. If the cookie is non-persistent, expires attributes are 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 expiration time and default path for writing authentication tickets to cookies.
The above process is based on Forms authentication, which completes the confirmation of user identity.
2. Create a web. config file in a protected folder such as manage. The content is as follows:
< Configuration >
<! -- Specify the access permission for the entire manage directory -->
< System . Web >
< Authorization >
<! -- Separate multiple roles with commas (,) -->
< Allow Roles = "Admin, user" />
< Deny Users = "*" />
</ Authorization >
</ System. Web >
<! -- Or Control the permissions of a page
<Location Path = "announcelist. aspx">
<System. Web>
<Authorization>
<Allow roles = "admin"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Location>
<Location Path = "configinfo. aspx">
<System. Web>
<Authorization>
<Allow roles = "users"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Location>
-->
</Configuration>
Note: The configuration content can also be added to the web. config file of the system. Note the following:
........
</ System. Web >
< Location Path = "Manage/announcelist. aspx" >
< System . Web >
< Authorization >
< Allow Roles = "Admin" />
< Deny Users = "*" />
</ Authorization >
</ System. Web >
</ Location >
</Configuration>
<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, the user can log on and confirm the identity, and 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 ). genericprincipal. the identity attribute is a formsidentity object. This object has a name attribute, which is the identifier of this 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.
3. logon page
// Logon button
Private Void Button#click ( Object Sender, system. eventargs E)
{
// The object class adminuservo corresponds to the adminuser User table.
Adminuservo = New Adminuservo ();
adminuservo. uname = username. text. trim ();
adminuservo. upwd = userpwd. text. trim ();
adminuservo. lastip = httpcontext. current. request. userhostaddress;
adminuservo. lasttime = datetime. now;
bool flag = ( New logindao ()). chk (adminuservo);
If(FLAG)
{
//This statement can be used for non-role authentication:
//System. Web. Security. formsauthentication. setauthcookie (username. Text. Trim (), false );
// Create Role authentication information, write the role information to userdata
Setlogincookie (adminuservo, adminuservo. roles. tolower ());
Httpcontext. Current. response. Redirect ( " Main. aspx " );
}
Else
{
Httpcontext. Current. response. Write ( " Logon Failed " );
}
}
// Setlogincookie Method
Public Static Void Setlogincookie (adminuservo U, String Roles)
{
// Create an identity authentication ticket object
Formsauthenticationticket ticket = New Formsauthenticationticket ( 1 , U. uname, datetime. Now, datetime. Now. addminutes ( 30 ), False , Roles, " / " );
// Encrypted serialization verification ticket as a string
String Hashticket = Formsauthentication. Encrypt (ticket );
Httpcookie usercookie = New Httpcookie (formsauthentication. formscookiename, hashticket );
Httpcontext. Current. response. Cookies. Add (usercookie );
}
Formsauthenticationticket parameter description:
Formsauthenticationticket (
Int version, // set to 1. The version number is automatically provided by the system.
String name, // user ID to obtain the username associated with the authentication cookie
Datetime issuedate, // cookie sending time, set to datetime. Now
Datetime expiration, // get the cookie expiration date/time
Bool ispersistent, // whether the cookie is persistent (set as needed. If it is set to persistent, The expires setting of the cookie must be set when sending the cookie). If a persistent Cookie has been issued, returns true. Otherwise, the authentication cookie is restricted within the browser lifecycle.
String userdata, // obtain the application definition string stored in the cookie. Here, use the role string prepared above to separate it with commas (,).
String cookiepath // return the cookie sending path. Note: the path of the form is set to "/", which must be the same as the path for sending the cookie, because the path is used to refresh the cookie. The form is case-sensitive, which is a protection measure to prevent the URL in the site from being case-insensitive.
);
4. Global. asax. CS
Protected Void Application_authenticaterequest (Object sender, eventargs E)
{
Httpapplication app = (Httpapplication) sender;
Httpcontext CTX = App. context; // Obtain the httpcontext object of this HTTP Request
If (CTX. User ! = Null )
{
If (CTX. Request. isauthenticated = True ) // Only Authenticated Users can perform role verification.
{
System. Web. Security. formsidentity fi = (System. Web. Security. formsidentity) CTX. User. identity;
System. Web. Security. formsauthenticationticket ticket = Fi. ticket; // Get authentication ticket
String Userdata = Ticket. userdata;// Restore role information from userdata
String [] Roles = Userdata. Split ( ' , ' ); // Convert role data into a string array to obtain relevant role information.
CTX. User = New System. Security. Principal. genericprincipal (FI, roles ); // In this way, the current user has the role information.
}
}
}
NOTE: If httpmodule is usedCodeIt should be added to the authenticaterequest event.