Several security verification methods for ASP. NET

Source: Internet
Author: User
Tags configuration settings
How to use form Authentication

ASP. NET security authentication. There are four authentication modes: "Windows", "form", "Passport", and "NONE. "Windows" and "NONE" do not play a protection role and are not recommended. I have never used "Passport", alas ...... So I have to talk about "form" certification. I plan to divide it into three parts:

Part 1 -- How to Implement from authentication;

Part 2: Practical Application of form authentication;

Part 3: Single Sign on)

Part 1 how to use form Authentication

1. Create a test project

For better description, it is necessary to create a test project ("formtest" for the time being), which contains three pages (default. aspx, login. aspx, userinfo. aspx ). What? No one will create a project or add a page? What should I do? I think it's okay: drag it out, call it back, learn from kindergarten ......

2. modify web. config

1. Double-click Web. config in the project (No, cannot find pp)

2. Find the following text <Authentication mode = "Windows"/> and change it:

<Authentication mode = "forms">

<Forms loginurl = "login. aspx" name = ". aspxauth"> </Forms>

</Authentication>

3. Replace <authorization> <allow users = "*"/> </authorization>

<Authorization> <deny users = "&"> </deny> </authorization>

There is nothing to say here, just copy it. However, some people may make a mistake as follows:

<Authentication mode = "forms">

<Forms loginurl = "login. aspx" name = ". apsx"> </Forms>

<Deny users = "&"> </deny>

</Authentication>

If you want to ask who put <deny users = "&"> </deny> in <authentication>, I would be honored to tell you that it was me n years ago: <authentication> and <authorization> both start with the auth letter and end with the ation. Why? I think they are a group of English words that cannot be memorized ......

3. Write. CS code-Logon and exit

1. logon code:

A. Introduced in books

Private void btn_login_click (Object sender, system. eventargs E)

{

If (this. txt_username.text = "admin" & this. txt_password.text = "123456 ")

{

System. Web. Security. formsauthentication. redirectfromloginpage (this. txt_username.text, false );

}

}

B. I have been searching for N for a long time.

Private void btn_login_click (Object sender, system. eventargs E)

{
If (this. txt_username.text = "admin" & this. txt_password.text = "123456 ")
{

System. Web. Security. formsauthentication. setauthcookie (this. txt_username.text, false );

Response. Redirect ("default. aspx ");

}
}

The two types of cookies can be issued after verification, that is, they pass verification. difference:

Method A) returns the request page after verification, which is commonly known as "from where to where ". For example, you can directly enter http: // localhost/formtest/userinfo In the IE address bar before logging on. aspx, the user will see the login. aspx & returnurl = userinfo. aspx. After the user name and password are entered, the system returns the corresponding page based on the "returnurl" value.

Method B) two steps are taken: after the verification is passed, the cookie is directly issued, and the jump page will be designated by the programmer. This method is mostly used in the system where default. aspx uses the framework structure.

2. Exit code:

Private void btn_logout_click (Object sender, system. eventargs E)
{

System. Web. Security. formsauthentication. signout ();

}

Iv. How to determine whether the verification is successful and obtain the verified user information

Sometimes, you need to determine whether the user has logged on to the same page and then display different la S. Some people like to use the session to judge, and I do not oppose this kind of practice. Here I just want to tell you there is another method and read the following code:

If (user. Identity. isauthenticated)
{

// You have passed the verification. Do you know what to do?

}

User. identity also has two attributes: authenticationtype (authentication type) and name (User Name). Note that the name attribute is the user. identity. name will get, when the verification passes (redirectfromloginpage or setauthcookie), we bring the first parameter This. txt_username.text. This parameter is very important and related to various types ...... In all kinds of situations, let's talk about this and break it down ......
Flexible Use of deny and allow in form authentication and Protection of. HTM files

Part 2 practical application of form Authentication

Scope of application of Web. config

When you create a project, vs. Net creates a fixed web. config file in the project root directory. In addition to the project root directory, you can also create web. config in any directory. The condition is that application-level nodes can only appear in Web. config in the root directory. I am not sure about the application-level nodes. I didn't invented my computer. I didn't create Microsoft, and C # was not my final idea. I don't know anything about the gods, so I don't know it's normal. Even so, as long as it does not report an error, it is correct.

For the scope of the web. config settings, remember the following two points:

1. Web. config settings apply to all files in the directory and all the objects in its subdirectories (inherit: Sub-parent with parent name)

2. The web. config settings under the subdirectory will overwrite the settings inherited by the parent directory (overwrite: the county officials are not as competent as they are now)

I would like to ask you a question: is there a configuration file that is more effective than the root directory web. config? After reading the third part, we will be able to understand the problem.

6. Learn to reject and use allow

Go back to the test project "formtest" we created in the first round. To verify the project, we have to have a user name and password according to international practice. So, are these users created by the Administrator in the database, or are these users registered and reviewed by the administrator. As long as it is not an ordinary idiot, we all know that we should select the latter. Don't you mention that some of my company's projects are actually managed by the Administrator to connect to the database to create an account. It's a special dumb. Let's leave him alone, add two pages honestly-register the page (register. aspx) and audit page (auditing. aspx ).

The problem is coming to the fore. When you try register. aspx and want to access it, you suddenly feel that something is wrong. Why did you go back to the login page? Check whether the URL is login. aspx & returnurl = register. aspx. What should I do? The user can access the registration page without an account? (This is a nonsense. If you have an account, you can register it .) I often say to my colleagues, "the way is people come up !!"

1. Create a directory named public to store some public files, such as perpetual calendar and scripts ......

2. In Solution Explorer, right-click the directory public and add a web. config

3. delete all the preceding web. config content. Leave the following only:

<& XML version = "1.0" encoding = "UTF-8" &>

<Configuration>

<System. Web>

<Authorization> <allow users = "*"/> </authorization>

</System. Web>

</Configuration>

It's not easy to get started. According to the "Overwrite" principle, we know that the above Web. config will replace the <authorization> node settings in the root directory web. config, that is:

<Allow users = "*"/> replace <deny users = "&"> </deny>

Note: "allow" allows meaning; "*" indicates all users;

"Deny" indicates "deny"; "&" indicates anonymous users;

Therefore, files in the public directory are accessible to all users, including unauthenticated users. Drag register. aspx in and no one will stop you from browsing.

In addition to the registration page, we also mention an audit page (auditing. aspx), audit permissions are generally in the hands of administrators or supervisors, and do not want others to browse this page (truth is often in the hands of a few people, this is also impossible), what should I do? "The way is people come up with something ...... Create an Administrator directory named managesys, and add another Web. config under this directory. The content is as follows:

<& XML version = "1.0" encoding = "UTF-8" &>

<Configuration>

<System. Web>

<Authorization>

<Allow users = "admin"/>

<Deny users = "*"/>

</Authorization>

</System. Web>

</Configuration>

System. Web. Security. formsauthentication. setauthcookie (this. txt_username.text, false); // The cookie is issued after verification.

I have previously stressed that the first parameter is very important. To what extent? Speaking of this, I am afraid everyone on Earth knows it-it is the basis of allow and deny. Assume that you enter "admin", that is, this. txt_username.text = "admin"; then, after entering the system, he will be able to access the webpage under the managesys directory, and all other idle people will be rejected.

To consolidate the above content, we will leave a homework assignment for everyone: This project is used by two departments, each of which has some specific pages for users of this department to browse and use, how can I use the web. config to achieve the effect? Similarly, the answer is displayed in the third part.

VII. decentralization and centralization

At first glance, it is like Marxism-Leninism, *** ideology, and the dialectical relationship in Deng Xiaoping theory. Everyone can rest assured that, even if they are studying science, they only understand that "they hold high the great banner of programmers, write code as the center ". Stop ......

So far, our test project "formtest" already has two directories and three web pages. config. more and more config, such as common file upload functions. A large number of web. config files are distributed in different directories, Which is annoying to maintain. Can we manage them in a centralized manner? What should we do? "The solution is ......" Hey, someone should say it first. Yes, "the solution is really just for people to come out." I don't say, are you just a cool companion? Joke: to let more people remember this sentence, I plan to tell you how to centralize management.

To centralize management, you have to use the <location> node and path attributes. In this project, we put the settings in the public and managesys directories in the web. config directory under the root directory, as shown below:

<& XML version = "1.0" encoding = "UTF-8" &>

<Configuration>

<Location Path = "public">

<System. Web>

<Authorization>

<Allow users = "*"/>

</Authorization>

</System. Web>

</Location>

<Location Path = "managesys">

<System. Web>

<Authorization>

<Allow users = "admin"/>

<Deny users = "*"/>

</Authorization>

</System. Web>

</Location>

<System. Web>

<! -- The content of web. config in the original root directory will not be listed here -->

</System. Web>

</Configuration>

Please note that

1. The <location> node is located on a sub-node of <configuration>. It is in parallel with the original <system. Web>.

2. The <location> node only needs to be placed into the content of the <system. Web> node in the corresponding subdirectory web. config.

8. Additional Protection

The second part is about to end. Now it's 04:50 am. It's easy for me. The purpose of authentication is to prevent others from browsing pages illegally or using certain functions without permission. Of course, there is no absolute security in the world. Now MD5 encryption has been cracked by Chinese people, which is the best example.

Careful people may have discovered that ASP. Net Security authentication only applies to. aspx,. ascx ...... And other ASP. NET files, but "Ignore" common pages and files, such as. htm and. js. jpg. Follow these steps to protect the file type you want to protect.

1. Open Internet Information Service (IIS) manager → right-click the project virtual → properties, as shown in

(Screen. Width-461) window. Open ('HTTP: // loads); "src =" http://blog.csdn.net/images/blog_csdn_net/cityhunter172/85935/r_aspxForm01.JPG "border = 0>)

2. Click "Configure". The following dialog box is displayed:

(Screen. Width-461) window. Open ('HTTP: // loads); "src =" http://blog.csdn.net/images/blog_csdn_net/cityhunter172/85935/r_aspxForm02.JPG "border = 0>)

3. Double-click the application extension of. aspx → view the content of the dialog box, for example:

(Screen. Width-461) window. Open ('HTTP: // loads); "src =" http://blog.csdn.net/images/blog_csdn_net/cityhunter172/85935/r_aspxForm03.JPG "border = 0>)

4. Copy the full path name of the executable file, click Cancel, and return to the previous dialog box. Click Add"

5. paste the copied content (my system is mounted on drive D, so the content is D: \ windows \ Microsoft. net \ framework \ v1.1.4322 \ aspnet_isapi.dll) → enter the suffix. htm → enter the action limit as "Get, Head, post, debug" (you can choose all for convenience)

6. Click "OK" → add htmlpage1.htm to the project → enter http: // localhost/formtest/htmlpage1.htm in the address bar of the IE browser → view the test results

Finally, let's send you a piece of Web. config settings. It's really difficult to go to bed.

<Location Path = "decisive battle against the Forbidden City">

<System. Web>

<Authorization>

<Allow users = "ye Gu City"/>

<Allow users = "Ximen snow blowing"/>

<Deny users = "*"/>

</Authorization>

</System. Web>

</Location>

<Location Path = "Golden Temple ridge">

<System. Web>

<Authorization>

<Allow users = "people with waist ribbons"/>

<Deny users = "*"/>

</Authorization>

</System. Web>

</Location>
ASP. NET Security Authentication (III)

After reading this, write your own practices (beginner level)

In fact, <location> is not only useful for folders, but also for pages. If there is a page that does not need to be verified (for example, default. aspx), write it like this under the <location> node:

<Location Path = "home. aspx">
<System. Web>
<Authorization>
<Allow users = "&"/>
</Authorization>
</System. Web>
.............
(Many permission control pages can be added in the middle)
..............
</Location>

The results are the same. The following content is posted on msdn.

<Location Path = "path"
AllowOverride = "True | false"/>

Optional attributes

Attribute options

The path application specifies the resource for configuration settings. Use <location> with the missing path property to apply the configuration settings to the current directory and all its sub-directories. If the <location> path attribute is not used and AllowOverride is set to false, the configuration setting cannot be changed through the Web. config file in the subdirectory.

AllowOverride specifies whether the configuration settings can be overwritten in the web. config file in the quilt directory.
True indicates that the configuration settings can be overwritten. The default value is true.
False indicates that the configuration settings cannot be overwritten.

Example
The following example allows anonymous users to access the logon. ASPX page.
<Configuration>
<Location Path = "Logon. aspx">
<System. Web>
<Authorization>
<Allow users = "&"/>
</Authorization>
</System. Web>
</Location>
</Configuration>

In the following example, only the size limit of the uploaded files on the specified page is set to kb.
<Configuration>
<Location Path = "uploadpage. aspx">
<Httpruntime maxrequestlength = "128"/>
</Location>
</Configuration>

The following example prevents the Web. config file from being changed in the configuration settings quilt directory.
<Configuration>
<Location AllowOverride = "false"/>
</Configuration>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.