ASP.NET Safety Certification (1)
- How to use Form form certification
Author: Han Yu Feng (cityhunter172)
sequence
The code writes N for a long time, I always want to write something else. This is not, in order to integrate two projects, make Single Sign on, and some people call "single sign-on". After checking the relevant documents, I finally realized it, and now I will share it with everyone. Perhaps everyone will ask: "This is not in conformity with the title?" Don't worry, before the pen, I thought of some of the problems I had encountered when I used Form certification, and some of the techniques used in the use process (it is speculative Also ^ _ ^). At the beginning of the occasion, the language level didn't drop. The exam often wrote, so the writing level is limited, please also ask everyone. By the way, I am not only limited, not only the programming ability is not very good. This article is for everyone to learn exchanges. Welcome the masses of the masses to carry the eggs and hold the flowers. Comment. Reprinted, please indicate the original creator, the cold Yufeng is also, not very grateful!
The nonsense is also almost the same, the words retired, the security certification of ASP.NET, has a total of "windows" "form" "none" four verification mode. "Windows" and "None" did not protect the role, not recommended; "Passport" I have not used it, oh ... so I have to tell "Form" certification. I intend to divide three parts:
Part 1 - How to achieve from certification;
Part II - FORM certification actual combat application;
Part III - Single Sign On
How to use Form form certification
First, create a new test item
For better instructions, it is necessary to create a new test item (forentic "formtest", including three pages (Default.aspx, Login.aspx, UserInfo.aspx). What? Some people will not create a new project, will not add a page? Do you ask me? I don't think so: drag out, retrieve the original borrow, learn from the kindergarten ...
Second, modify Web.config
1. Double-click Web.Config in the project (no, can't find PP)
2. Find the following text
authentication>
3, find
Third, write .CS code - login and exit
1, login code:
A, books introduced
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 found Ni Niki found it.
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 above two can issue authentication cookies, which is verified, distinguished:
Method A) Refers to the verification, return the request page, commonly known as "where to play". For example: The user is not logged in to enter http://localhost/formtest/Userinfo.aspx directly in the IE address bar, then the user will see the login.aspx? ReturnURL = userinfo.aspx, enter the username and password after logging in The system will return the corresponding page according to the value of "returnurl"
Method B) is divided into two steps: After verifying, the cookie is issued directly, and the jump page will be specified by the programmer, this method is used for the system of default.aspx using the frame structure.
2, exit the code:
Private void btn_logout_click (Object Sender, System.Eventargs E)
{
System.web.security.formsauthentication.signout ();
}
Fourth, how to determine the verification and obtain the verification user information
Sometimes, in the same page, it is necessary to judge whether the user is already logged in, then rendering different layouts. Some people like to use session to judge, I don't oppose such practices, here I just want to tell you that there is another way, and look at the following code:
User.Identity.isauthenticated) {
// You have passed the verification, know what to do?
}
User.Identity also has two attributes AuthenticationType (Verification Type) and Name (User Name), everyone should pay attention to the name property, user.Identity.name here will be obtained, verify it, verify it, we bring The first parameter this.txt_username.text. This parameter is very important, related to all ... all kinds of situations, what other words, and listen to the decomposition ...
Part 2 Form certification actual combat application
To last words, I simply said the usage of form form certification. Maybe everyone feels too simple, it should be "sprinkling water" "small kiss (small means)" for those big masters. Today, let's take a picture: ancient six doors, reject Ye Ling City; Dongmen is not blowing, blowing a snow surname; ribbon makes a voucher, drapeab the Forbidden City.
V. WEB.CONFIG scope
When new projects are created, VS.NET creates a content fixed web.config in the project root directory. In addition to the root of the project, you can also create web.config in any directory, and the condition is that the application level node can only appear in the web.config of the root directory. As for which is the application level node, this problem, in fact, I am not very clear, huh, huh. The computer is not my invention. Microsoft is not what I created. C # is not what I said, and the gods don't know, so I don't know it is normal. That is, as long as it does not report an error, it is right.
Remember the following two points regarding web.config settings
1. Web.config settings will act on all files in the directory and all the stuff in their subdirectory (inheritance: children with the father's surname)
2, the web.config setting under the subdirectory will overwrite the settings inherited by the parent directory (overwriting: the county official is not as good as the current tube)
Give everyone a question: Is there a profile that is larger than the root of the root directory web.config? After reading the third part, you will know.
6. Learn to refuse and use it to allow
Back to our new test project "formtest" in the first round, since it is necessary to verify, with a customer name and password. Then, these users are administrators to build it in the database, or the user registration, the administrator is good. As long as it is not a general idiot, I know the latter. Don't say, our company really has an individual project is an administrator to join the database to build an account. It belongs to the more special stupid. Let's don't learn him, or you have a new page - Register page (Register. " ASPX) and audit page (Auditing.aspx).
The problem finally turned out to surface, when you do register.aspx, I suddenly feel bad when I want to access it, how come back to the login page? You carefully look at the website, is it: login.aspx? ReturnURL = register.aspx. What to do, the user is because there is no account to access the registration page? (This sentence is purely nonsense, there is an account who also ran to register.) I often said to my colleague: "The way is to come out !!" 1, create a directory public, used to store some public files, such as Wan years, script ...
2. Right-click on "Solution Explorer" to click on the directory public, add a web.config
3. Delete the content of the above web.config, leaving only the following:
xmlversion = "1.0" eNCoding = "UTF-8"?>
configure>
It is not easy to cut into the topic. Depending on the principle of overlay, we know the above Web.config will replace the
Note: "Allow" Allowed; "*" means all users;
"Deny" refuses to mean; "?" Means anonymous users;
Therefore, files in the public directory allow all people to browse, including unfounded users. Drag the register.aspx, no longer stop you from browsing.
In addition to the registration page, we also mention an auditing page (Auditing.aspx), audit permissions are generally in the administrator or supervisor, do not want others to browse this page (the truth is often in the hands of a few people, this is also What should I do if I don't have a thing? "The way is that people want to come out" Oh ... New administrators' directory ManageSys, add a web.config in this directory. The content is as follows:
xmlversion = "1.0" eNCoding = "UTF-8"?>
authorization>
configure>
Now how can I know who is "admin", this question is like "I have a hole in my sole" - I don't know, you don't know I know. Leaders less (if there is a draft fee, I have to write a few words, hehe ...), do you still remember my end in the first part? What, forget! Penalty, go back to see it, remember it again. Stand, come back! When I think of your memory, I will not be relieved, the first part of the browsing website is http://blog.9cbs.net/cityhunter172/624043.aspx, returning here URL is http: //blog.9cbs.net/cityhunter172/Archive/2005/11/13/528463.aspx is good, no matter where those who have a bad, everyone will continue to look down.
System.Web.Security.FormSauthentication.seTauthCookie (this.txt_username.text, false); // Get a cookie
I have emphasized before, pay attention, the first parameter is very important, what extent? Speaking of this, I am afraid that the earth people know - it is the basis for Allow and Deny. If the user fills in "admin" is this.txt_username.text = "admin"; then after entering the system, he can access the webpage under the ManageSys directory, other legacy, etc. will be rejected.
In order to consolidate the above content, leave an out-of-school job for everyone: This project has two departments, of which each department has some specific pages for this department only to use users. How do I use Web.config to achieve effect? Similarly, the answer is announced in the third part.
Seven, scattered and concentrated
At first glance, it is like Marxism-Leninism, Mao Zedong Thought, and Deng Xiaoping 's dialectical relationship. Everyone is relieved, even the academics, only understand "the great banner of programs, and write code centered". stop……
To this end, our test item "formtest" already has two web.config, with the diversification of user needs, Web.config will have more and more, such as commonly used file upload functions, and more. Numerous web.config is distributed in different directories, and it is more annoying to maintain it. Can you focus on management? "The way is ..." Hey, someone said first. Yes, "The way is indeed a man who wants to come out", I don't say, are you only one side? I am joking, in order to let more people remember this sentence, I plan to tell you the way to centrally manage.
To focus on management, you have to use the
XML Version = "1.0" encoding = "UTF-8"?>
authorization>
location>
authorization>
location>
configure>
Need to remind
1, the location of the
2,
Eight, additional protection
The second part is to end, the time is now 4:50 in the morning, I am easy to me. The purpose of the certification is to prevent others from illegal to browse the page, or use certain features without permission. Of course, there is no absolute security in the world. Today, MD5 encryption is cracked by our people, it is the best example.
The careful person may have discovered the safety certification of ASP.NET to work only for the ASP.NET files such as .aspx, .ascx ..., "turn it out of the ordinary page and the file", such as .htm, .js, .jpg Wait. You can protect the file type you want to protect by following these steps.
1. Open Internet Information Services (IIS) Manager → Right-click on this item virtual → property, as shown below
(http://blog.9cbs.net/Images/blog_9cbs_net/cityhunter172/85935/r_aspxform01.jpg)
2. Click the button "Configuration" and the following dialog box appears:
(http://blog.9cbs.net/Images/blog_9cbs_net/cityhunter172/85935/r_aspxform02.jpg)
3. Double-click the .aspx application extension → check the contents of the dialog, as shown below:
(http://blog.9cbs.net/Images/blog_9cbs_net/cityhunter172/85935/r_aspxform03.jpg)
4. After copying the full path name of "executable file" → Click "Cancel" to return to the previous layer dialog box → Click the button "Add"
5, paste the content you just copied (my system is installed in the D disk, so the content is D: /Windows/Microsoft.Net/framework/v1.1.4322/ASPNET_ISAPI.DLL) → After filling, the name is .htm → fill in the action limit "Get, Head, Post, Debug" (for convenience, you can choose all)
6, finally click "OK" → Add htmlpage1.htm to the project → Enter http://localhost/formTest/htmlpage1.htm → watch the test effect directly in the address bar of the IE browser
Finally, send everyone a web.config setting, sleep, it is really sleepy.
authorization> system.web>
location>
authorization>
location>
Part III Realize single sign-on (SINGLESIGNON)
"Waiting for a long time, I finally waited until today, I wrote it for a long time, but the response of netizens made me have some sadness. I hope that I have finally hoped that today, I have to write this article, those who are cold It has long been unequering, and it is tired to say "" lyrics "today" new interpretation). Looking at the BLOG article of the people is a piece of pick, then you will look at yourself: "No one cares, true ... no ... Nai ... Hey, no one cares about me, still go home." "Hey, not start yet Write, how can I get? Go back to do? "Go back to write the homework, have you done the extracurricular homework? (Note: http://blog.9cbs.net/cityhunter172/Archive/2005/11/13/528463. Extracurricular operations arranged in the second section of the second section: This project has two departments, each of which Some specific pages are only available for this department users. How do I use Web.config to achieve effect?)
I don't know how many people do homework, and in fact, the answer is not difficult. Just try to verify the user name and password, get the user's department name or department code, which will be used as the basis of judgment. It is best not to use the department's digital ID, which is not conducive to future maintenance.
Have a secret, the average person I don't tell him. The Path property of the
Ok, then I will uncover the mystery of "Profile of the Scheme of Big Genes Web.config", it is hiding in the Windows system directory, dominating the legendary Machine.config of the entire .NETFramework configuration. ! ! Let's take a warm applause, welcome our mysterious knight's shining debut ...
Nine, Machine.config
Machine.config, gender, age unknown, family origin: XML. A certain place in the operating system directory of "Yun Shenzhi" (Note: C: / Windows [or WinNT] /microsoft.net/framework/v1.1.4322 [or v1.0.3705] / config), control Native configuration of "more online" .Netframework. Next, explain its content and its relationship with Web.config.
After "Panasonic asked the boy", we finally found this hobby, open a look, hey, there are more than 3,700 lines! ! "Call me how can I not have to pass, I just want to see it is a structure, but I really have too much tissue ..." I still remember the words that I often say to my colleague: "The method is people thinking!" It Isn't there more than 3,700 rows, then we don't have to come out of the twenty-one, put it out. Is it not an XML? Let's still do it, rename "Machine.xml". Then use the IE browser to open the changing the changing the face, and close the node with the comment one by one. This time you see it, is it a sense of accomplishment? If you want to thank me, let me see your comments below this article. A lot of benefits, huh, huh. Is Machine.config and Web.config? Four words - parental relationship. I remember that I mentioned two points when I explain the WEB.CONFIG role range - inheritance and coverage (see http://blog.9cbs.net/cityhunter172/Archive/2005/11/1528463 .ASPX), here is equally applicable.
1. The settings in Machine.config will work to all sites and their virtual directories running in this unit, and encounter subdirectories will continue.
2, the settings in web.config will override the corresponding node settings that inherited from Machine.Config
Speaking of this, tell everyone a secret - "There is no secret in the world, knowing more people, and it is not a secret secret!"
a, all content in Machine.Web> Node can appear in the web.config in the project root directory, that is, the content that can be in the web.config is already listed in Machine.config. ;
b, in which
<% @ Page language = "c #" codebehind = "Webform1.aspx.cs" autoeventwireup = "false" inherits = "fromTest.webform1" ValidateRequest = "false"%>
Ten, prerequisite for single sign in Singlesignon
I have said so much about Machine.config, which is to achieve single sign-on board, which is single sign-on (SINGLESIGN)? From the literal understanding of logging in, usually used in the ASP.NET distributed environment (Forms authentication across multiple applications on a single server or in the network field). For an example, it is like SOHU (Sohu) and chinren (China alumni) practice, I don't need to log in in chinaren after Sohu login. Taiwan and Hong Kong also called Singlesignon as "single logo".
To implement this feature, the primary condition is a set of keys for encryption and verification encryption. They are located in Machine.config, modify the FigStkey = "172" CopyrightKey = "cityhunter172" validationKey = "AD117F2F286CDCB15A9D1D4535E16DB0248026939 ** AUTHOR ** CITYHUNTER172 **** WEBSITE ** 172 * MEIBU * COM **** MAILTO ** CITYHUNTER172 @ 126 * COM ***** F2F286CDCB15A9D1D4535E16DB0248026939" SecondKey = "Meibu" DecryptionKey = "3C89AE62AD117F2F286CDCB15A9D1D4535E16DB0248026939" Validation = "SHA1" Thirdkey = "COM" /> 1. ValidationKey is a key used to verify the encrypted data. The minimum length is 40 characters (20 bytes), the maximum length is 128 characters (64 bytes). 2, DecryptionKey is a key for encrypting data. There are only 16 characters (8 bytes) in length and 48 characters (24 bytes). 3. Validation is the encryption type used in data verification. Have three ways of "sha1" "md5" "3DES" 4, everyone refers to the above THIS.TEXTBOX2.TEXT = "HT" "TP" ": //" firstKey "." Secondkey "." thirdKey Everyone will back up Machine.config before modifying. If you go, don't blame, I don't want to remind you. The above key is not Hu, which is next to the method of generating a key. We drag the WebForm1.aspx mentioned in the previous section into the public directory of this project, and drag into a TextMode = Multiline on the page and write a button event with a button. Event and function: PrivatevoidButton1_Click (ObjectSender, System.Eventargse) { StringDecstr = this.createKeystring (int.Parse (this.textBox1.text); Stringvalstr = this.createKeystring (int.Parse (THIS.TEXTBOX2.TEX); This.TextBox3.text = string.format (" } /// /// Generate an encrypted strong random Key value /// summary> /// /// DecryptionKey valid value is 8 or 24; /// ValidationKay's effective value is 20 to 64 /// param> PRIVATESTRINGCREATEKEYSTRING (INTI) { System.Security.cryptography.rngcryptoserviceProvider RNG = newsystem.security.cryptography.rngcryptoserviceProvider (); // encrypted random number generator Byte [] bt = new byte [i]; RNG.GETBYTES (BT); // Filling by encryption-type strong random value sequence System.Text.StringBuilder str = newsystem.text.stringbuilder (); For (intj = 0; j
{ Str.Append (String.Format ("{0: x2}", BT [j])); // Convert Hexadecimal text } Returnstr.tostring (); } Every time you click the button to generate a key, you may wish you a few more points. Switch to the HTML view, go to the first line of Webform1.aspx to remove ValidateRequest = "false", then try more to try, see what it will, 嘿 ......... Eleven, Site Site Signal Site Example The text produced by the above TEXTBOX3 is covered in Machine.Config, and now your machine has a single sign-on condition. Everyone can create a project formtest2, log in directly from FormTest2, enter the URL of the default.aspx in FormTest (http://localhost/formtest/default.aspx), and vice versa. The following combined examples explain: even in Shandong's every step of the technology website applied for a free secondary domain name 172.meibu.com, and downloaded a dynamic domain parsing client for each 2.0 version. Now use the ADSL Coaled Internet, which means that my computer has become a web server, and supports SQLServer. The Oracle space is up to 200G how to get it, enough cow, oh. The project coming up will have a wound digital website, the authority management system, the IT internal management network, and the above three projects are the top right to develop. The so-called full power is to write from the data set of the .CS code to JavaScript, and finally go to the art. ^ _ ^ I made these three unsatisfactory projects into single-point login mode, plus the main page of the integrated site, and four places can be logged in. Because the user table structure is different, only one entry can enter after entering, it will not be wrong when the jump site is, that is, the integration page is logged in. Now I want to leave the Sheng Qi Digital this site separately, and the rest of the two sites continue to realize single sign-on, what should I do? Or is my ASP.NET space is rent, the service provider is definitely impossible to make me modify Machine.config, I don't do it? "The way is to come out !!", according to the above Machine.config and Web.config, we can put the 1. Web.config for the permission management system project is used for Form authentication settings authentication> 2. Web.config for IT internal management network project is used for Form authentication settings authentication> Everyone may try to try it, even in good agreement, because the truth is the only way to test truth. You don't try to do it yourself, look at me is hard to improve this. Don't worry, I already know what you want, listen to me slowly explain: a) Two project web.cinfig's b) The cookie name of the two projects must be the same, that is, the name attribute in c) Pay attention to case sensitive In the process of integration, I will talk to everyone to everyone, so as to avoid the same way. 1) First, it should be the problem of user management, and the users of the two projects are integrated. It is not an easy task. The principle is to create a new Table only to store account and password, do the association with the account, write triggers, Do the synchronization between tables; 2) Do not expect two items to use session to pass values, and the session of the two applications is unable to share. Some people have put the class library (compiled .dll document) into the same bin folder to implement the session sharing, this practice actually combines two items into one application, not what we want, Reason is very simple: what should I do if SOHU and CHINAREN server? 3) The pass value between the project can be implemented with a cookie. In the first part of the third quarter (http://blog.9cbs.net/cityhunter172/archive/2005/11/06/524043.aspx) We introduce as long as you run the system.Web.Security.FormSauthentication.SetAuthCookie method can be implemented Log in, the essence of single sign-on is a cookie containing authentication tickets to share between projects. Next, it is necessary to introduce you to the usage of cookies in .NET. Twelve, cookie usage in ASP.NET Everyone may be like me, very few uses cookies, pass parameters, save variables in ASP.NET, and use more session or viewstate and hidden controls. Some simply use "?" Request. 1, catalog stored by cookie Cookie is stored in the client's stuff, placed in the "TempoterInternetFiles" directory, so there is security issues. Everyone can find specific locations in the following ways: Open Control Panel → Internet Options → General → Internet Temporary File → Settings → You can see "Current Location", → Click "View File" to open the folder directly, you can also click "Moving Folder" changes its location. Refer to the picture below (http://blog.9cbs.net/cityHunter172/85935/r_aspxform04.jpg with http://blog.9cbs.net/cityHunter172/85935/r_aspxform05.jpg) 2, the validity of cookie From the figure above, we can clearly see the "deadline" of each cookie document (ie, for the validity period). During the validity period, when the user administrator logged in to the computer, when I accepted 172.meibu.com, IE, along with the name "cookie: administrator@172.meibu.com", together with the name "cookie: administrator@172.meibu.com" while the requested page. Send to the server. If the document contains a value of multiple cookies, the deadline is based on the final failure period. 3, cookie type Here we are divided into two types: a) Instant Refers to closing the browser (all IE browsing 172.meibu.com's IE), the cookie invalidates that this cookie will not appear in the "TempoterInternetFiles" directory. In fact, it also has a deadline, "0001-01-01" b) persistent type It is a cookie that has been specified in the specific "deadline", which can be found in the "TempoRenetternetFiles" directory. 4, cookie content Double-click Open "Cookie: Administrator@172.meibu.com", we see the following, as shown below (http://blog.9cbs.net/Images/blog_9cbs_net/cityhunter172/85935/r_aspxform06.jpg): In the figure, "■" is a newline character, if you want to break what the pot is asking me how to know. I will tell you very happy: This is the experience! At the moment of learning C #, take the first Windows program - the experience of the notepad to turn the knife and save the document. So the format read from the server is shown below (http://blog.9cbs.net/cityHunter172/85935/r_aspxform07.jpg): 5, release cookie on the ASP.NET page Sending the above cookie. CS code is: System.Web.httpcookie CK = New Httpcookie ("ckvalue0"); CK ["Author"] = "cityhunter"; Ck.expires = system.datetime.now.addminutes (10); // If you do not specify, it is an instant Cookie. //ck.path="/formtest/ManageSys"/formtest/ManageSys";// set cookie's virtual path, pay attention to the beginning of "/", otherwise it is invalid cookie; please take a look at it with the Cookie Document "Name" in the guest room Relationship with "Internet Address" Response.cookies.add (ck); CK = newhttpcookie ("ckvalue1"); // Renew Cookie named CKValue1 Ck.expires = system.datetime.now.addminutes (20); // Failure after 20 minutes CK ["e_mail"] = "cityhunter172@126.com"; // Set the E_MAIL value in CKValue1 CK ["PersonalWeb"] = "172.meibu.com"; Response.cookies.add (ck); // Add this cookie 6, retrieve the value of the released cookie Response.write (Request.Cookies ["ckvalue0"] ["author"] " Response.write (Request.Cookies ["ckvalue1"] ["e_mail"] " Response.write (Request.Cookies ["CKValue1"] ["PersonalWeb"]); I haven't had homework for a long time (why do you have this?), This third article, but spend two weeks of spare time debugging, summing up, writing, saying that time is expensive, I don't know how I spend these time How much silver is exchanged? Change the money, I see it is not expected, I can get a comment of you, even satisfied. Remember, your comment is to continue writing the power. Job: Give cookie to the following value, how to get its correct value CK ["STR1"] = "2222"; CK ["Str"] = "STR0 = 11111 & str1 = 223"; It is certain that Request.Cookies ["ckvalue1"] ["str"] does not get "Str0 = 11111 & str1 = 223" strings, everyone will try REQUEST.COOKIES ["ckvalue1"] ["str1"] will get Fantastic strings. Tip: Using Server.urlencode () and Server.URLDECode () Thirteen, issue permanent verification cookies Finally ... finally ... the last chapter, suddenly look back, the ocean sprinkles twelve chapters. I didn't expect to write an essay when I wrote the essay, but I can also have a few words of the article. I have to admire myself! Looking back, a big fairy person ... How long is forever indeed? How long is it permanently? Only the sky knows. When you log in to 9CBS, do you pay attention to a check box for a "no longer logged in within 2 weeks", how did it do? Have you encountered such a confusion: In the execution system.web.setauthcookie, it is clear that CREATEPERSISTENTCOOKIE is TRUE to close the browser directly to access the website? Below we explain to this issue, and introduce how to manually create authentication tickets and add cookies. System.Web.Security.FormSauthenticationTicket TK = newsystem.Web.Security.FormSauthenticationTicket 1, // Specify version number: can be specified at will "Admin", // login username: WEB.CONFIG System.Datetime.now, // Published System.datetime.now.addyears (100), // Failure time: 100 years later, it is forever for a long time. False, // Is it a lasting cookie: I have not found anything, at least I still don't know, there will be explanation below. "Test User Data" // User Data: Available (System.Web.Security.FormSidentity User.Identity) .ticket.userData ); Stringstr = system.web.security.formsauthentication.encrypt (tk); // Encrypted authentication ticket // Declare a cookie, named the Name property of System.Web.httpcookieck = newhttpcookie (System.Web.Security.FormsAuthentication.formscookiename, STR); // Specify cookie to Web.config
"); // not explained it
");
configure>
It is not easy to cut into the topic. Depending on the principle of overlay, we know the above Web.config will replace the
Note: "Allow" Allowed; "*" means all users;
"Deny" refuses to mean; "?" Means anonymous users;
Therefore, files in the public directory allow all people to browse, including unfounded users. Drag the register.aspx, no longer stop you from browsing.
In addition to the registration page, we also mention an auditing page (Auditing.aspx), audit permissions are generally in the administrator or supervisor, do not want others to browse this page (the truth is often in the hands of a few people, this is also What should I do if I don't have a thing? "The way is that people want to come out" Oh ... New administrators' directory ManageSys, add a web.config in this directory. The content is as follows:
XML Version = "1.0" encoding = "UTF-8"?>
authorization>
configure>
Now how can I know who is "admin", this question is like "I have a hole in my sole" - I don't know, you don't know I know. Leaders less (if there is a draft fee, I have to write a few words, hehe ...), do you still remember my end in the first part? What, forget! Penalty, go back to see it, remember it again. Stand, come back! When I think of your memory, I will not be relieved, the first part of the browsing website is http://blog.9cbs.net/cityhunter172/624043.aspx, returning here URL is http: //blog.9cbs.net/cityhunter172/Archive/2005/11/13/528463.aspx is good, no matter where those who have a bad, everyone will continue to look down.
System.Web.Security.FormSauthentication.seTauthCookie (this.txt_username.text, false); // Get a cookie
I have emphasized before, pay attention, the first parameter is very important, what extent? Speaking of this, I am afraid that the earth people know - it is the basis for Allow and Deny. If the user fills in "admin" is this.txt_username.text = "admin"; then after entering the system, he can access the webpage under the ManageSys directory, other legacy, etc. will be rejected.
In order to consolidate the above content, leave an out-of-school job for everyone: This project has two departments, of which each department has some specific pages for this department only to use users. How do I use Web.config to achieve effect? Similarly, the answer is announced in the third part.
Seven, scattered and concentrated
At first glance, it is like Marxism-Leninism, Mao Zedong Thought, and Deng Xiaoping 's dialectical relationship. Everyone is relieved, even the academics, only understand "the great banner of programs, and write code centered". stop……
To this end, our test item "formtest" already has two web.config, with the diversification of user needs, Web.config will have more and more, such as commonly used file upload functions, and more. Numerous web.config is distributed in different directories, and it is more annoying to maintain it. Can you focus on management? "The way is ..." Hey, someone said first. Yes, "The way is indeed a man who wants to come out", I don't say, are you only one side? I am joking, in order to let more people remember this sentence, I plan to tell you the way to centrally manage.
To focus on management, you have to use the
XML Version = "1.0" encoding = "UTF-8"?>
authorization>
location>
authorization>
location>
(This article comes from the blog of Han Yufeng CityHunter172: http://blog.9cbs.net/cityhunter172 Site: http://172.meibu.com)
configure>
Need to remind
1, the location of the
2,
Eight, additional protection
The second part is to end, the time is now 4:50 in the morning, I am easy to me. The purpose of the certification is to prevent others from illegal to browse the page, or use certain features without permission. Of course, there is no absolute security in the world. Today, MD5 encryption is cracked by our people, it is the best example.
The careful person may have discovered the safety certification of ASP.NET to work only for the ASP.NET files such as .aspx, .ascx ..., "turn it out of the ordinary page and the file", such as .htm, .js, .jpg Wait. You can protect the file type you want to protect by following these steps.
1. Open Internet Information Services (IIS) Manager → Right-click on this item virtual → property, as shown below
(http://blog.9cbs.net/Images/blog_9cbs_net/cityhunter172/85935/r_aspxform01.jpg)
2. Click the button "Configuration" and the following dialog box appears:
(http://blog.9cbs.net/Images/blog_9cbs_net/cityhunter172/85935/r_aspxform02.jpg)
3. Double-click the .aspx application extension → check the contents of the dialog, as shown below:
(http://blog.9cbs.net/Images/blog_9cbs_net/cityhunter172/85935/r_aspxform03.jpg)
4. After copying the full path name of "executable file" → Click "Cancel" to return to the previous layer dialog box → Click the button "Add"
5, paste the content you just copied (my system is installed in the D disk, so the content is D: /Windows/Microsoft.Net/framework/v1.1.4322/ASPNET_ISAPI.DLL) → After filling, the name is .htm → fill in the action limit "Get, Head, Post, Debug" (for convenience, you can choose all)
6, finally click "OK" → Add htmlpage1.htm to the project → Enter http://localhost/formtest/htmlpage1.htm → watch the test effect directly in the address bar of the IE browser
Finally, send everyone a web.config setting, sleep, it is really sleepy.
authorization>
location>
authorization>
location>
TRACKBACK: http://tb.blog.9cbs.net/trackback.aspx?postid=528463
[Original] ASP.NET Safety Certification (3)
- Single Sign on the FORM form confirmation (Single Sign "
Author: Han Yu Feng (cityhunter172)
The third part achieves single sign-on (SINGLE SIGN ON)
"Waiting for a long time, I finally waited until today, I wrote it for a long time, but the response of netizens made me have some sadness. I hope that I have finally hoped that today, I have to write this article, those who are cold It has long been unequering, and it is tired to say "" lyrics "today" new interpretation). Looking at the BLOG article of the people is a piece of pick, then you will look at yourself: "No one cares, true ... no ... Nai ... Hey, no one cares about me, still go home." "Hey, not start yet Write, how can I get? Go back to do? "Go back to write the homework, have you done the extracurricular homework? (Note: http://blog.9cbs.net/cityhunter172/Archive/2005/11/13/528463. Extracurricular operations arranged in the second section of the second section: This project has two departments, each of which Some specific pages are only available for this department users. How do I use Web.config to achieve effect?)
I don't know how many people do homework, and in fact, the answer is not difficult. Just try to verify the user name and password, get the user's department name or department code, which will be used as the basis of judgment. It is best not to use the department's digital ID, which is not conducive to future maintenance.
Have a secret, the average person I don't tell him. The Path property of the
Ok, then I will uncover the mystery of "The Profile of the Scope of Big Directory Web.config", which is hidden in the Windows System Directory, which dominates the legendary Machine, the entire .NET Framework configuration. CONFIG! ! Let's take a warm applause, welcome our mysterious knight to debut ... 9. Machine.config
Machine.config, gender, age unknown, family origin: XML. A certain place in the operating system directory of "Yun Shenzhi" (Note: C: / Windows [or WinNT] /microsoft.net/framework/v1.1.4322 [or v1.0.3705] / config), control Native configuration of "more on the next level" .NET Framework. Next, explain its content and its relationship with Web.config.
After "Panasonic asked the boy", we finally found this hobby, open a look, hey, there are more than 3,700 lines! ! "Call me how can I not have to pass, I just want to see it is a structure, but I really have too much tissue ..." I still remember the words that I often say to my colleague: "The method is people thinking!" It Isn't there more than 3,700 rows, then we don't have to come out of the twenty-one, put it out. Is it not an XML? Let's still do it, rename "Machine.xml". Then use the IE browser to open the changing the changing the face, and close the node with the comment one by one. This time you see it, is it a sense of accomplishment? If you want to thank me, let me see your comments below this article. A lot of benefits, huh, huh.
Is Machine.config and Web.config? Four words - parental relationship. I remember that I mentioned two points when I explain the WEB.CONFIG role range - inheritance and coverage (see http://blog.9cbs.net/cityhunter172/Archive/2005/11/1528463 .ASPX), here is equally applicable.
1. The settings in Machine.config will work to all sites and their virtual directories running in this unit, and encounter subdirectories will continue.
2, the settings in web.config will override the corresponding node settings that inherited from Machine.Config
Speaking of this, tell everyone a secret - "There is no secret in the world, knowing more people, and it is not a secret secret!"
a, all content in Machine.Web> Node can appear in the web.config in the project root directory, that is, the content that can be in the web.config is already listed in Machine.config. ;
b, in which
<% @ Page language = "c #" codebehind = "Webform1.aspx.cs" autoeventwireup = "false" inherits = "fromTest.Webform1" ValidateRequest = "false"%> 10, single sign-on "Prerequisites
I have said so much about Machine.config, which is to achieve single sign-on board, which is Single Sign on? From the literal understanding of logging in, usually used in the ASP.NET distributed environment (Forms authentication across multiple applications on a single server or in the network field). For an example, it is like SOHU (Sohu) and chinren (China alumni) practice, I don't need to log in in chinaren after Sohu login. Taiwan and Hong Kong also called SINGLE SIGN ON "Single Logo".
To implement this feature, the primary condition is a set of keys for encryption and verification encryption. They are located in Machine.config, modify the
1. ValidationKey is a key used to verify the encrypted data. The minimum length is 40 characters (20 bytes), the maximum length is 128 characters (64 bytes).
2, DecryptionKey is a key for encrypting data. There are only 16 characters (8 bytes) in length and 48 characters (24 bytes).
3. Validation is the encryption type used in data verification. "SHA"
1
"
"MD
5
"
Three ways "3DES"
4, everyone refers to the above
THIS.TEXTBOX2.TEXT = "HT" "TP" ": //" firstKey "." Secondkey "." thirdkey
Everyone will back up Machine.config before modifying. If you go, don't blame, I don't want to remind you. The above key is not Hu, which is next to the method of generating a key. We drag the WebForm1.aspx mentioned in the previous section into the public directory of this project, and drag into a TextMode = Multiline on the page and write a button event with a button. Event and function:
Private void Button1_Click (Object Sender, System.Eventargs E)
{
String decstr = this.createKeystring (int.Parse (THIS.TEXTBOX1.TEXT));
String valstr = this.createKeystring (int.parse (this.textbox2.text);
This.TextBox3.text = string.format ("
}
///
/// Generate an encrypted strong random Key value
/// summary>
/// key of key:
/// DecryptionKey has a valid value of 8 or 24;
/// ValidationKay's effective value of 20 to 64
/// param>
Private string createKeystring (INT i)
{
System.Security.cryptography.rngcryptoserviceProvider RNG = New System.Security.cryptography.rngcryptoServiceProvider (); // Encrypted Rander Summer
Byte [] bt = new byte [i];
RNG.GETBYTES (BT); // Filling by encryption-type strong random value sequence
System.Text.StringBuilder str = new system.text.stringbuilder ();
For (int J = 0; j
{
Str.Append (String.Format ("{0: x2}", BT [j])); // Convert Hexadecimal text
}
Return str.tostring ();
}
Every time you click the button to generate a key, you may wish you a few more points. Switch to the HTML view, go to the first line of Webform1.aspx to remove ValidateRequest = "false", then try more to try, see what it will, 嘿 .........
Eleven, Site Sign in Single Sign On)
The text produced by the above TEXTBOX3 is covered in Machine.Config, and now your machine has a single sign-on condition. Everyone can create a new project formtest2, log in directly from FormTest2, enter the URL of the default.aspx in FormTest (http: // localhost / formtest / default.aspx), and vice versa.
The following combined examples explain: even in Shandong's every step of the technology website applied for a free secondary domain name 172.meibu.com, and downloaded a dynamic domain parsing client for each 2.0 version. Now use ADSL Coarable Internet, which means that my computer has become a web server, and supports SQL Server, Oracle space up to 200 g.
I want to get how to get, enough, oh. The project coming up will have a wound digital website, the authority management system, the IT internal management network, and the above three projects are the top right to develop. The so-called full power is to write from the data set of the .CS code to JavaScript, and finally go to the art. ^ _ ^ I made these three unsatisfactory projects into single-point login mode, plus the main page of the integrated site, and four places can be logged in. Because the user table structure is different, only one entry can enter after entering, it will not be wrong when the jump site is, that is, the integration page is logged in.
Now I want to leave the Sheng Qi Digital this site separately, and the rest of the two sites continue to realize single sign-on, what should I do? Or is my ASP.NET space is rent, the service provider is definitely impossible to make me modify Machine.config, I don't do it? "The method is to come out !!" as follows:
1. Web.config for the permission management system project is used for Form authentication settings
authentication>
117F 2F 286CDCB 15A 9D1D4535E16DB0248026939 ** Author ** cityHunter172 **** Website ** 172 * meibu * com **** mailto ** cityhunter172 @ 126 * com ***** f 2F 286CDCB 15A 9D1D4535E16DB0248026939 "DecryptionKey =" 3C 89AE62AD 117F 2F 286CDCB 15A 9D1D4535E16DB0248026939 "Validation =" sha1 "/> authentication> c) Pay attention to case sensitive In the process of integration, I will talk to everyone to everyone, so as to avoid the same way. 1) First, it should be the problem of user management, and the users of the two projects are integrated. It is not an easy task. The principle is to create a new Table only to store account and password, do the association with the account, write triggers, Do the synchronization between tables; 2) Do not expect two items to use session to pass values, and the session of the two applications is unable to share. Some people have put the class library (compiled .dll document) into the same bin folder to implement the session sharing, this practice actually combines two items into one application, not what we want, Reason is very simple: what should I do if SOHU and CHINAREN server? 3) The pass value between the project can be implemented with a cookie. In the first part of the third quarter (http://blog.9cbs.net/cityhunter172/archive/2005/11/06/524043.aspx) We introduce as long as you run the system.Web.Security.FormSauthentication.SetAuthCookie method can be implemented Log in, the essence of single sign-on is a cookie containing authentication tickets to share between projects. Next, it is necessary to introduce you to the usage of cookies in .NET. Twelve, cookie usage in ASP.NET Everyone may be like me, very few uses cookies, pass parameters, save variables in ASP.NET, and use more session or viewstate and hidden controls. Some simply use "?" Request. 1, catalog stored by cookie Cookie is stuffed in the client, placed in the Temporary Internet Files directory, so there is security issues. Everyone can find specific locations in the following ways: Open Control Panel → Internet Options → General → Internet Temporary File → Settings → You can see "Current Location", → Click "View File" to open the folder directly, you can also click "Moving Folder" changes its location. Referring next to FIG (http://blog.9cbs.net/images/blog_9cbs_net/cityhunter172/85935/r_aspxForm04.jpg and http://blog.9cbs.net/images/blog_9cbs_net/cityhunter172/85935/r_aspxForm05.jpg):2 , Cookie's validity period 2, the validity of cookie 2, the validity of cookie From the figure above, we can clearly see the "deadline" of each cookie document (ie, for the validity period). During the validity period, when the user administrator logged in to the computer, when I accepted 172.meibu.com, IE, along with the name "cookie: administrator@172.meibu.com", together with the name "cookie: administrator@172.meibu.com" while the requested page. Send to the server. If the document contains a value of multiple cookies, the deadline is based on the final failure period. 3, cookie type Here we are divided into two types: a) Instant Refers to the closing browser (all IE browsing 172.meibu.com IE), cookies invalid, such cookies will not appear in the "Temporary Internet Files" directory. In fact, it also has a deadline, 0001-01-01 " b) persistent type It is a cookie that has been specified in the "Temperature Internet Files" directory. 4, cookie content Double-click Open "Cookie: Administrator@172.meibu.com", we see the following, as shown below (http://blog.9cbs.net/Images/blog_9cbs_net/cityhunter172/85935/r_aspxform06.jpg): In the figure, "■" is a newline character, if you want to break what the pot is asking me how to know. I will tell you very happy: This is the experience! Even from learning C #, take the first Windows program - Notepad to open the knife, save the documentation. So the format read from the server is shown below (http://blog.9cbs.net/cityHunter172/85935/r_aspxform07.jpg): 5, release cookie on the ASP.NET page Sending the above cookie. CS code is: System.Web.httpcookie CK = New Httpcookie ("ckvalue0"); CK ["Author"] = "cityhunter"; Ck.expires = system.datetime.now.addminutes (10); // If you do not specify, it is an instant Cookie. //ck.path="/formtest/managesys "; // Set the virtual path of the cookie, pay attention to" / "to begin, otherwise it is invalid cookie; please take a look at it with the Cookie document" name "in the room Relationship with "Internet Address" Response.Cookies.Add (CK); CK = New httpcookie ("ckvalue1"); // Renew Cookie named CKValue1 Ck.expires = system.datetime.now.addminutes (20); // Failure after 20 minutes CK ["e_mail"] = "cityhunter172@126.com"; // Set the E_MAIL value in CKValue1 CK ["PersonalWeb"] = "172.meibu.com"; Response.cookies.add (ck); // Add this cookie 6, retrieve the value of the released cookie Response.write (Request.Cookies ["ckvalue0"] ["author"] " Response.write (Request.Cookies ["ckvalue1"] ["e_mail"] " Response.write (Request.Cookies ["CKValue1"] ["PersonalWeb"]); I haven't had homework for a long time (why do you have this?), This third article, but spend two weeks of spare time debugging, summing up, writing, saying that time is expensive, I don't know how I spend these time How much silver is exchanged? Change the money, I see it is not expected, I can get a comment of you, even satisfied. Remember, your comment is to continue writing the power. Job: Give cookie to the following value, how to get its correct value CK ["STR1"] = "2222"; CK ["Str"] = "STR0 = 11111 & str1 = 223"; It is certain that Request.Cookies ["ckvalue1"] ["str"] is not "Str0 = 11111 & str1 = 223 " This string, everyone will try REQUEST.COOKIES ["ckvalue1"] ["str1"] will get unexpected strings. Tip: Using Server.urlencode () and Server.URLDECode () Thirteen, issue permanent verification cookies Finally ... finally ... the last chapter, suddenly look back, the ocean sprinkles twelve chapters. I didn't expect to write an essay when I wrote the essay, but I can also have a few words of the article. I have to admire myself! Looking back, a big fairy person ... How long is forever indeed? How long is it permanently? Only the sky knows. When you log in to 9CBS, do you pay attention to a check box for a "no longer logged in within 2 weeks", how did it do? Have you encountered such a confusion: In the execution system.web.setauthcookie, it is clear that CREATEPERSISTENTCOOKIE is TRUE to close the browser directly to access the website? Below we explain to this issue, and introduce how to manually create authentication tickets and add cookies. System.Web.Security.FormSauthenticationTicket TK = new system.Web.Security.FormSauthenticationTicket 1, // Specify version number: can be specified at will "Admin", // login username: WEB.CONFIG System.Datetime.now, // Published System.datetime.now.addyears (100), // Failure time: 100 years later, it is forever for a long time. False, // Is it a lasting cookie: I have not found anything, at least I still don't know, there will be explanation below. "Test User Data" // User Data: Available (System.Web.Security.FormSidentity User.Identity) .ticket.userData ); String str = system.web.security.formsauthentication.encrypt (tk); // Encrypted authentication ticket // Declare a cookie, named the name property of System.Web.httpcookie CK = New httpcookie (System.Web.Security.FormsAuthentication.formscookiename, STR); // Specify cookies to Web.config Ck.path = system.Web.Security.FormSauthentication.formscookiepath; // This sentence is very important, less, even if this cookie specifies as a persistent cookie in the authentication ticket, it is just the real-time cookie closes the browser. Therefore, I said: I really don't know What is the use of persistence cookies in an identity ticket. Ck.expires = system.datetime.now.addyears (100); Response.cookies.add (ck); // Add to the room postscript This series of articles have a total of three parts, which have been completed for a month ( 2005-11-05 ~ 2005-12-06 ). The above is some of my experience I have learned and used in practice, and I will share it with everyone. The code is commissioned. If you have any questions, you can find me at the 9CBS Forum (http://community.9cbs.net/), my ID is cityhunter172 (available this ID to send a short message to me), nickname is cold Yifeng, welcome everyone to criticize. In addition, it is found that when some websites are reproduced in my article, they not only delete some of them, but they don't tolerate the authors and have not found the source. Here, I hope that everyone will be reproduced, be sure to indicate the author is "Ci Yufeng (CityHunter172), thank you. TRACKBACK: http://tb.blog.9cbs.net/trackback.aspx?postid=545301 Original] ASP.NET Safety Certification (4) - Smartfully implement the Form form certification cross-site, single sign-on across servers (Single Sign ON) Author: Han Yu Feng (cityhunter172) Part IV Supplement of FORM Certification The first three articles were published in the 9CBS forum, the effect is like "god fart - really different (reverse) ring." In order to thank the netizens' enthusiasm and support, this is not, after the brewing, cultivation, special intended to prepare this fourth ring. We used Form certification to realize single sign-on, just as the netizen said, only under the same domain. For a single sign-on across domain name, in addition to using Passport authentication, we can still use form authentication, just to pay attention to methods. The so-called "mountain does not turn into water, people do not turn". First, cross-domain solving ideas Search for keyword "passport" on MSDN 2003, even "Passport Authentication Provider". The article tells the principle of passport's certification, a total of 8, I don't have much to say, everyone will look at it. One sentence, causing an even note: "... responded to the query string contains a encrypted Passport cookie ...". It is also this sentence that has the following ideas. The so-called pass or not, its essence is to detect that there is no valid cookie, using form, and use Passport, all Cookie works. That is, we just have to pay the valid cookie to the client after logging in to the client. Second, cross-domain name, single sign-on method of cross-server 1. How to simulate cross-domain names, SINGLE SIGN ON across the server As long as the browsing website is different, it is equivalent to different domain names, and at least three of this unit. Although they are the same project, they cannot share session and cookies, which will not share authentication tickets: a). http://localhost/formtest/login.aspx b) http://127.0.0.1/formtest/login.aspx c). http://my_computer_name/formtest/login.aspx // Browse the station with the computer name d) http://192.168.0.8/FormTest/login.aspx // Browse the site in NIC address e) http://172.meibu.com/formtest/login.aspx // Have an international domain name 2, how to submit it to other pages in ASP.NET Probably known for VIEWSTATE, ViewState is saved on the client. I don't know everyone, ASP.NET is equipped for each .aspx page, and is parsed to save ViewState with a hidden control value of a name = "__viewstate". Each page is submitted, the server checks that the value of the control is tampered, so it is destined to .aspx can only be submitted to this page. The server is dead, people are alive, we can't be defined by these rules frames, we must write the program to live. Let's enter your username and password from http://localhost/formtest/login.aspx, then submit it to http://127.0.0.1/formtest/public/logintransfer.aspx. Login.aspx and logintransfer.aspx include a username input box, a password input box, a login button. Add the following code in the Login.aspx page: this.btn_login.attributes ["onclick"] = "SINGLESIGN ()"; / / Specify the execution script event Insert the following script on the Login.aspx page: Function SingLesignon () { // You can only change the object submitted by the script. Document.GtelementByid ("form1") .Action = "http://127.0.0.1/FormTest/public/logintransfer.aspx?fromurl=" window.location.href; // Turn the value in the hidden control __viewstate to logIntransfer.aspx resolution, which is subject to the actual value Document.all .__ viewstate.value = "DDWTMTKYODUZMTMYNZS7PV1CP2RAXUCR5HGYF8ILX9 / EMKY8"; } script> Precautions a). Logintransfer.aspx appears and its ID must be able to find Login.aspx b). The ID of the control must be consistent, and it can correspond one by one. c). About __ViewState, it is independent of the page control ID, regardless of the URL to this page, currently I only know the number, type, name space (Namespace formtest.public), and the existing viewState relationship . Everyone is tested to browse http://127.0.0.1/formtest/public/logintransfer.aspx, view the value seen by the page source file. d) After submit, the BTN_Login_Click event in logintransfer.aspx will be triggered and executed. 3, basic ideas The login page of each site will submit the username with the password to the Logintransfer.aspx, and each site requires an increased cookie page to add the encrypted authentication cookie to the client. This is the feasibility plan for finally determined after a test. 4, the first idea - Tianqiaohua What is a celestial flower, that is, putting the cookie after logging in, just like Tianxian, the scene is, the scene is spectacular. Below start writing code: To better distinguish, we will be responsible for adding a cookie page to a separate naming: a). Http://localhost/formtest/public/addcookie_a.aspx b) http://127.0.0.1/formtest/public/addcookie_b.aspx c) http://my_computer_name/formtest/public/addcookie_c.aspx The same functionality is the same, so the code is the same. Private Void Page_Load (Object Sender, System.EventArgs E) { String from = request ["fromurl"]; // Start URL path String next = Request ["nextURL"]; // The URL of the jump String Key = Request ["cookieticket"]; // Encrypted cookie text IF (key! = null && key! = "") { System.web.httpcookie ck = new httpcookie (system.web.security.formiename, key); Ck.path = system.Web.Security.FormSauthentication.formscookiepath; Ck.expires = system.datetime.now.addyears (100); Response.cookies.add (ck); // Added encrypted authentication tickets to the guest room String url = next.split (';') [0]; // Split the next page that will be jumped from the URL Next = Next.Replace (URL ";", ""); // Bring the next round of jump IF (URL! = "") { / / Skip to the next page Response.Redirect (URL "? Cookieticket =" " " & fromURL = " from" & nextURL = " NEXT); } Else // No next page can be jumped { Response.Redirect (from); // Back to the start page } } } Next, write the code of logintransfer.aspx: // Page constant allLoginURL stores all the addCookie.aspx's URL, pay attention to; separation Public const string allLoginURL = "http://localhost/formtest/public/addcookie_a.aspx;" "http://127.0.0.1/formtest/public/addcookie_b.aspx;" "http://my_computer_name/formtest/public/addcookie_c.aspx;"; I have already told above, how to click on the login button btn_login in login.aspx BTN_Login submit the username with the password to LogInTransfer.aspx, and perform BTN_Login_Click events in Logintransfer.aspx. Private void btn_login_click (object sender, system.eventargs e) { String from = request ["fromurl"]; // Start URL path String next = this.AllloginURL; // Due to the same control ID, it is obtained by the username and password submitted by Login.aspx. IF (this.txt_loginname.text == "admin" && this.txt_password.text == "123456") { System.Web.Security.FormSauthenticationalTicket TK = new system.Web.Security.FormSauthenticationTicket (1, "admin", system.datetime.now, system.datetime.now.addyears (100), false, "test user data"); String key = system.Web.security.formsauthentication.encrypt (tk); // Get encrypted authentication ticket string String url = next.split (';') [0]; // Split the next page that will be jumped from the URL Next = Next.Replace (URL ";", ""); // Bring the next round of jump Response.Redirect (URL "? Cookieticket =" key "& get =" from "& nextURL =" next); // Skip to the next page } } 5, the second idea - after the shooting day After the shooting day, it means that the user is jumping. If he is a "fire pit", you have to jump in it, because the user is God. We add a pass page mypassport.aspx, and the verification cookies are issued directly to http://127.0.0.1/formtest/mypassport.aspx by http://127.0.0.1/formtest/public/logintransfer.aspx. Don't tell me, you won't, if you don't, it's no anecdote, you have to ask you to look back, even in the third article, how to make a permanent verification cookie (http://blog.9cbs .NET / CityHunter172 / Archive / 2005/12/06 / 545301.ASPX). You also need a jump page for the springboard MyTransfer.aspx. MyPassport.aspx code:
HREF = "MyTransfer.aspx? goto = http://localhost/formtest/public/addcookie_d.aspx"> Beautiful angel
HREF = "MyTransfer.aspx? goto = http:///127.0.0.1/formtest/public/addcookie_e.aspx"> Happy paradise MyTransfer.aspx code: Private Void Page_Load (Object Sender, System.EventArgs E) { / / Get an authentication ticket System.Web.Security.FormSauthenticationalTicket TK = (System.Web.Security.FormSidentity) User.Identity) .ticket; String key = system.Web.security.formsauthentication.encrypt (tk); // Different skewers each time the encrypted string is different String next = Request ["goto"]; // will jump URL Response.Redirect (URL "? Cookieticket =" key); // jump to the next page } AddCookie_d.aspx, addcookie_e.aspx, addcookie_f.aspx code: String Key = Request ["cookieticket"]; // Encrypted cookie text IF (key! = null && key! = "") { System.web.httpcookie ck = new httpcookie (system.web.security.formiename, key); Ck.path = system.Web.Security.FormSauthentication.formscookiepath; Ck.expires = system.datetime.now.addyears (100); Response.cookies.add (ck); // Added encrypted authentication tickets to the guest room Response.Redirect ("../ index.aspx"); // Jump to you really want to take customers } 6, review Both common: a). Each site requires a login submission point, one to add a cookie page. b). Because you only rely on the authentication cookie to identify the identity, a computer cannot log in to two accounts at the same time. c) There are different levels of security hazards. Both of the two: (Days of the sky below "to open the woman", the post-shooting day is referred to as "post") a). The day is one-time distribution of cookies, if the site is more, it is still required to handle it. Then, the opposite is the opposite, and the site is not afraid. b). During the process of decline, if the trip is stuck, a wrong handling mechanism is needed to return. The post is not required. c). The day will browse the site you want to see directly after logging in; then, it must enter from the panel page of the pass. Depending on the above questions, give some suggestions: a) Don't use permanent cookies, you should specify the expiration time of the authentication ticket, pay attention to the validity of the cookie. b). Add other validation information or store user IDs in UserData, authenticated tickets. c) In the case of a smooth network, such as a local area network, the site is relatively small, it is recommended to choose a celestial woman. Doing a jump between 50 sites should not exceed 10 seconds (provided that it is compiled, and is not initial access). Third, cross-domain name, cross-server exit method, as long as it understands "Tianzhuhua", it is easier to quit. Prepare a page for exiting for each site, as follows: a). http://localhost/formtest/public/logout.aspx b) http://127.0.0.1/formtest/public/logout.aspx c) http://my_computer_name/public/formtest/logout.aspx Private Void Page_Load (Object Sender, System.EventArgs E) { System.Web.Security.FormSauthentication.signout (); // Delete authentication tickets in cookies String from = Request ["fromurl"]; String next = Request ["nextURL"]; String Url = Next.Split (';') [0]; Next = next.replace (url ";", ""); IF (URL! = "") { Response.Redirect (URL "? Get =" from "& nextURL =" next); } Else { Response.Redirect (from); } } Yes, there is another logoutTransfer.aspx., The code is even don't write, everyone is completed. Cold Yufeng (CityHunter172) 2005-12-31 18:22 Diction TRACKBACK: http://tb.blog.9cbs.net/trackback.aspx?postid=567479
"); // not explained it
");