ASP.NET safety certification

xiaoxiao2021-04-07  311

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 change it to:

">

3, find

in , I will be honored to tell you, it is N years ago: and It is the end of the AUTH alphabet, why is it similar; I can't think of the English word, I thought they were a group ...

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:

It is not easy to cut into the topic. Depending on the principle of overlay, we know the above Web.config will replace the node setting in the root-director web.config, namely:

"replace

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:

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 node and path properties. In this project, we put the directory PUBLIC with the settings under the root of the root directory, as follows:

Need to remind

1, the location of the Node is a child node in , which is parallel to the original

2, nodes only need to put the node content in the corresponding subdirectory web.config

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.

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 node in web.config can be a relative URL path for a specific page, as follows:

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 can appear on the page, such as: HTML view, in the first line of WebForm1.aspx Plus Node content validateRequest = "false" The meaning is not the value input to the WebForm1.aspx page text box, whether "<" ">", etc. Is inspected, the next section will be applied)

<% @ 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 node properties under the node, as follows:

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 Try to run the following statement in WebForm1.aspx:

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 ("", valstr, decstr);

}

///

/// Generate an encrypted strong random Key value

///

/// Key's valid length:

/// DecryptionKey valid value is 8 or 24; /// ValidationKay's effective value is 20 to 64

///

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 node into the project root directory Web.config's node. as follows:

1. Web.config for the permission management system project is used for Form authentication settings

2. Web.config for IT internal management network project is used for Form authentication settings

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 Node Make sure the following: ValidationKey, DecryptionKey, Validation

b) The cookie name of the two projects must be the same, that is, the name attribute in , here we unify it as Name = "172.meibu.com_project"

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"] "
"); // not explained it

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 "UserS attribute

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 , the corresponding value is the string after the authentication ticket is encrypted.

System.Web.httpcookieck = newhttpcookie (System.Web.Security.FormsAuthentication.formscookiename, STR);

// Specify cookie 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 Room

postscript

This series of articles have a total of three parts, which have been completed 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.

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 the keyword "passport" on the MSDN2003, 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, SingLesignon 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 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// owns 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 to the Login.aspx page: this.btn_login.attributes ["onclick"] = "SingLesignon ()"; // Specify the execution script event

Insert the following script on the Login.aspx page: