Go to http://www.cnblogs.com/stg609/archive/2009/03/12/1408296.html
Asp.net forms form verification experience and verification process analysis
Recently, a login page was designed to address security issues. I remember that in my course on ASP.net security, I mentioned that Asp.net provides four authentication procedures: 1. form authentication; 2. windows authentication; 3. passport authentication; 4. default Authentication. I especially talked about form authentication. I think that I have never used this authentication method before, so let's use it as a trainer.
Form Verification allows you to restrict user access based on users and roles. For example, we have a background management system. Only users who log on through the background login page can access any page in the background management system, in this case, we can use Form Verification (in the past, I wrote the judgment logic on every page. Now I think of it, the method in the past is really physical labor, and if you forget to write it, it will be troublesome ).
The experiment started (because it only records experience, some knowledge points are not mentioned here. It takes more time for everyone to spend extra time out of class. Some links are provided at the end of this Article for your reference)
Next, let's take an example of forms verification. In this example, two folders are created: user and Admin. login. aspx, index. aspx, and Web. config. To access the user folder as a normal user, you must first log on to the user logon interface before accessing the user's index. aspx. The Administrator must first log on to the admin logon interface before accessing index. aspx in Admin. Loginredirect. aspx, Web. config, and global. asax are available in the root directory of the website.
Directory structure:
How can we implement form verification?
1. configure the web. config (in the root directory of the website, Web. system. in the Web tag, modify the original <Authentication mode = "Windows"/> as the following code)
<Authentication mode = "forms">
<Forms name = "adminlogin" loginurl = "loginredirect. aspx">
</Forms>
</Authentication>
<Authorization>
<Allow users = "*"/>
</Authorization>
What does the above configuration mean?
First, there are two different configuration sections. Does authentication and authorization look very similar? You must never be fooled by your eyes. The two are different meanings. The former is "Verification" and the latter is "Authorization ".
Next, let's take a look at the "verify" configuration section.
Mode indicates the authentication method. There are four options: Windows, forms, passport, and none. The default value is windows. Select forms.
In the forms element, the name and loginurl are set.
Name indicates the cookie name. We will use cookies to save user information and send HTTP requests containing cookie information to the server. The server identifies the user based on the cookie information for further verification.
As the name suggests, loginurl is the address of the login page. If you do not have the permission to access a page, it will be redirected to this page.
There are many other elements. Please search for the relevant materials by yourself. I will also provide some links that I think are good at the end of the article.
After completing the "Verification" section, I will talk about the "Authorization" section.
Authorization naturally limits which users or roles can access and which users or roles cannot access. You can set <allow> and <deny>. <Allow users = "*"> indicates that all users are allowed to access the service. You may wonder if you want to restrict user access. Why are you allowed? That's because I just want everything under the root directory to be accessible to any user.
Let's take a look at the web. config in the two subfolders.
<Configuration>
<Location Path = "login. aspx">
<System. Web>
<Authorization>
<Allow users = "*"/>
</Authorization>
</System. Web>
</Location>
<System. Web>
<Authorization>
<Allow roles = "user"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Configuration>
In this configuration file, the content of the "Verification" section cannot be configured (the content can only be in the root directory of the virtual directory web. configuration in config), we can only configure the "Authorization" section. The above location indicates that authorization check is not required for this path, because I hope any user can access the login page, so everyone should think about it.
Other paths do not require Unlogged users or website administrators to log on. Therefore, <allow roles = "user"> is used to allow access by users with only the role as user, access is denied by any other user.
Similarly, let's look at the web. config In the Administrator directory. Please analyze it yourself.
<Configuration>
<Location Path = "login. aspx">
<System. Web>
<Authorization>
<Allow users = "*"/>
</Authorization>
</System. Web>
</Location>
<System. Web>
<Authorization>
<Allow roles = "manager"/>
<Deny users = "*"/>
</Authorization>
</System. Web>
</Configuration>
After the configuration, We need to write some Cs code. First, let's take a look at loginredirect. aspx. CS. Because, when we access any of the above sub-file pages, we will jump to this page first, but in fact I want to jump to the login page of the trusted sub-directory. Therefore, you need to make some judgments in this file.
String from = request. querystring ["returnurl"]; // each redirected page carries a returnurl value to retrieve the previous page
// Obtain the subdirectory name
String fromfilepath = from. substring (from. indexof ('/') + 1, from. indexof ('/', from. indexof ('/') + 1)-from. indexof ('/')-1 );
// Determine the jump link based on the subdirectory name
Switch (fromfilepath. tolower ())
{
Case "admin": Response. Redirect ("/admin/login. aspx"); break;
Case "user": Response. Redirect ("/user/login. aspx"); break;
}
Some may be strange. Since loginurl can be configured in the "Verification" section, cannot I directly jump to the corresponding login page of this directory for each directory implementation? Unfortunately, no direct solution has been found so far. If you have any solutions, please do not hesitate to give me some advice.
After redirecting to the login page, we should process the user's login time.
Protected void page_load (Object sender, eventargs E)
{
// Determine whether the user has logged on and the role is user
If (user. Identity. isauthenticated & User. isinrole ("user "))
{// If the verification succeeds, the system will jump directly to index. aspx.
Response. Redirect ("index. aspx ");
}
}
// Logon button event. For the sake of simplicity, I will directly judge the event using the username "user" and password "1". Of course, you can also read the event from the database.
Protected void btnlogin_click (Object sender, eventargs E)
{
If (tbusername. Text = "user" & tbpwd. Text = "1 ")
{
// Generate a verification ticket, including the user name, validity period, expiration time, permanent storage, and user data. Information about user roles is stored in user data.
Formsauthenticationticket ticket = new formsauthenticationticket (1, tbusername. Text, datetime. Now, datetime. Now. addminutes (30), true, "user ");
String cookiestr = formsauthentication. Encrypt (ticket); // encrypt the ticket
Httpcookie cookie = new httpcookie (formsauthentication. formscookiename, cookiestr );
/* Save it to the cookie. The cookie name must be the same as the name value we wrote in the configuration file. Because, when the cookie is kept locally, the next time you check the user permissions, it will automatically find the cookie with the same name as forms and send it to the server for verification. If the cookie cannot be found locally, the verification will naturally fail. */
Cookie. expires = ticket. expiration;
Cookie. Path = formsauthentication. formscookiepath;
Response. Cookies. Add (cookie );
Response. Redirect ("index. aspx"); // jump to index. aspx after successful login
}
}
/*
A ticket suddenly popped up here. Isn't it strange for some friends? What is the use of a ticket?
A ticket can also be understood as a credential (only users with creden。 can pass the check). It includes some user-related information written in the above comments. However, tickets cannot be directly transmitted to the server and must be carried through cookies. After receiving the cookie, the server extracts the ticket data and performs related operations.
*/
The same is true for login. aspx. CS in the admin folder. I will not go into details.
I almost forgot the last thing, that is, configuring roles for our users. We found that the role assignment function was not provided during ticket creation, so we can only use grobal. asax.
There is an application_authenticaterequest event in global. asax. This event will occur before the server determines whether the user's browser should jump. Therefore, you only need to configure the user role here.
Protected void application_authenticaterequest (Object sender, eventargs E)
{
If (httpcontext. Current. User! = NULL)
{// If the user passes verification, this item is not null
If (httpcontext. Current. User. Identity. isauthenticated)
{
If (httpcontext. Current. User. Identity is formsidentity)
{
Formsidentity id = (formsidentity) httpcontext. Current. User. identity;
Formsauthenticationticket ticket = ID. ticket;
String userdata = ticket. userdata; // retrieves role data
String [] roles = userdata. Split (',');
Httpcontext. Current. User = new genericprincipal (ID, roles); // reassign a role
}
}
}
}
You can download the entire project.
[Note: you cannot log on to the user interface and the administrator interface on the same computer. Because only one cookie can be retained using the forms name, if you log on to the administrator interface and then log on to the user interface, the original cookie value will be overwritten. Some friends use session to save user data as an experiment.]