ASP.net security Certification (iii): Single sign-on using form form authentication

Source: Internet
Author: User
Tags date config contains continue valid domain domain name root directory
Asp.net| Security

"Wait for a long time finally until today, wrote a long time finally on the end, but the response of netizens let me have some sadness." Hope for a long time to finally look forward to today, endure for a long time finally to write this article, those who are left out of the cold, tired does not say tired "(lyrics" Today "new interpretation). Look at People's Blog article comment is one after another, and then look at their own: "Nobody, really ..." No... Nigeria ... Alas, no one to ignore me, or go home. "Hey, haven't started to write, how did you go?" What are you doing back? "Go back to the writing industry, did you do your homework?" (Note: The assignment assigned by Http://blog.csdn.net/cityhunter172/archive/2005/11/13/528463.aspx in section sixth of section II: This project is used by two departments, Each of these departments have some specific pages for users to browse the use of the department, how to use Web.config to achieve results? )

I do not know how many people did the homework, in fact, the answer is not difficult. Only need to verify the user name and password, take the user's department name or department code, it as a basis for the judgement on the line. It is best not to use the department's digital ID, which is not conducive to future maintenance.

There is a secret that ordinary people I do not tell him. The path attribute of the <location> node in web.config can be a relative URL path to a specific page, as follows: <location path = "Managesys/auditing.aspx" >

Well, the next step is to uncover the mystery of "a configuration file larger than the root directory web.config," a legendary machine.config hiding in the Windows system directory that governs the entire. Net Framework configuration!! Below please everybody with the warm applause, welcome us this mysterious Warrior's shining debut ...

Nine, Machine.config

Machine.config, sex unknown, age unknown, family origin: XML. Deep in the "clouds do not know where" operating system directory of certain places (note: C:\WINDOWS "or WINNT" \microsoft.net\framework\v1.1.4322 "or v1.0.3705" \config), control the "higher level" of The native configuration of the. NET Framework. Next, briefly explain its content and its relationship with Web.config.

After "Panasonic asked the lad", we finally found the hermit, open a look, obediently, full of more than 3,700 lines!! "How can I not sad, I just want to see what is the structure, but the content is too much too cumbersome ..." Remember what I often say to my colleagues: "The way people think out!" "It is not more than 3,700 lines, then we do not care whether 37 can reach 21, to handcuff it out first." It's not an XML origin, so let's just do it again, and rename it "Machine.xml." Then use IE browser to open the makeover of the hermit, the node with the note one by one closure. This time you see, is it a sense of accomplishment? If you want to thank me, let me see your comments under this article. The more the more, hehe.

What is the relationship between Machine.config and web.config? Four words--parent-child relationship. Remember when I explained the scope of Web.config in the fifth section of Part two, I mentioned two points--inheritance and coverage (see http://blog.csdn.net/cityhunter172/archive/2005/11/13/528463.aspx), The same applies here.

1. The settings in Machine.config will be used to run all the sites and their virtual directories on this machine, and the subdirectories will continue to inherit.

2, the settings in Web.config will overwrite the corresponding node settings inherited from Machine.config

Speaking of this, and then tell us a secret-"there is no secret in the world, know more people, it is not a secret secret!" ”

A, machine.config <system.web> node all content can appear in the project root directory in the web.config, that is, the contents of the web.config in the Machine.config are listed in one by one;

b, where <pages> under <system.web> node can also appear on the page, such as: HTML view, in the first line of WebForm1.aspx plus <pages> The node content validaterequest= "False" (this means that the WebForm1.aspx page text box does not enter the value, contains "<" ">" and so on dangerous code to check, the next section will be used specifically)

<%@ Page language= "C #" codebehind= "WebForm1.aspx.cs" autoeventwireup= "false" inherits= "Fromtest.webform1" Validaterequest= "false"%>

Ten, single sign-on (Sign on) prerequisites

Previously said so much about Machine.config, are in order to achieve a single sign-on to pave the way, then what is a single point of entry Sign? The literal understanding is to log in in one place, often in a asp.net distributed environment (across multiple applications on a single server or in a Web farm) as Forms authentication. For example, like now Sohu (Sohu) and Chinren (China Alumni), I do not need to login after Sohu login. Taiwan and Hong Kong have also called the single Sign "one sign on".

The first condition for this functionality is the need for a set of keys for encrypting and verifying encryption. They are located in Machine.config, modifying the <machineKey> node properties under the <system.web> node as follows:

<machinekey firstkey= "172" copyrightkey= "Cityhunter172" ad117f2f286cdcb15a9d1d4535e16db0248026939**author**cityhunter172****website**172*meibu*com****mailto** cityhunter172@126*com*****f2f286cdcb15a9d1d4535e16db0248026939 "secondkey=" Meibu "decryptionKey=" 3c89ae62ad117f2f286cdcb15a9d1d4535e16db0248026939 "validation=" SHA1 "thirdkey=" com "/>

1. ValidationKey is the key for verifying encrypted data. The minimum length is 40 characters (20 bytes) and the maximum length is 128 characters (64 bytes).

2. DecryptionKey is the key used to encrypt data. The length is only 16 characters (8 bytes) and 48 characters (24 bytes).

3, validation for data validation using the encryption type. Three ways to have "SHA1" "MD5" "3DES"

4, the guys refer to above <machineKey> try to run the following statements in WebForm1.aspx:

This. TextBox2.Text = "HT" + "TP" + "://" +firstkey+ "." +secondkey + "." +thirdkey

Please back up your machine.config before you make any changes, but don't blame me for not reminding you. The above key is not random, then we introduce the method of generating the key.

We drag the WebForm1.aspx mentioned in the previous section into the public directory of this project, and then drag a textmode=multiline TextBox3 with a button on the page to write the buttons 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 ("<machinekey validationkey=\" {0}\ "decryptionkey=\" {1}\ "validation=\" sha1\ "/>", valstr,decstr);

}

<summary>

Generate cryptographically strong random Key value

</summary>

<param name= "I" >key effective length:

The valid value of DecryptionKey is 8 or 24;

Valid values for Validationkay are 20 to 64

</param>

private string createkeystring (int i)

{

System.Security.Cryptography.RNGCryptoServiceProvider rng = new  System.Security.Cryptography.RNGCryptoServiceProvider (); Cryptographic random number generator

byte[] bt = new Byte[i];

Rng. GetBytes (BT);//filling byte array with cryptographically strong random value Sequence

System.Text.StringBuilder str = new System.Text.StringBuilder ();

for (int j= 0;j<i;j++)

{

Str. Append (String. Format ("{0:x2}", Bt[j]); Hexadecimal text converted to uppercase

}

Return str. ToString ();

}

Each click button to generate a key is different, you may wish to more than a few times. Switch to HTML view, to WebForm1.aspx the first line of the validaterequest= "false" removed, and then a few more times Button1 try to see what effect, hehe ...

Sample site for single sign-on (Sign on)

The text generated by the above TextBox3 is covered in Machine.config, and now your machine has a single sign-on condition. We can create a new project FormTest2, from the FormTest2 login directly into the formtest Default.aspx URL (http://localhost/FormTest/Default.aspx), vice versa.

The following combination of examples: I have applied for a free two-level domain name 172.meibu.com for each step of the science and Technology website in Shandong, and downloaded the 4.0 version of the dynamic Domain name resolution client. Now use ADSL dial to surf the internet, which means my computer has become a WEB server, while supporting SQL Server, Oracle space up to how to do how to do it, enough cow, hey. The project to come up has the ring wins the digital website, the Authority management system, IT internal management network, above three projects are the doll person to develop entirely. The so-called full powers are written from the database stored procedures to the. cs code to JavaScript, and finally to the art of the artists are done. ^_^ I made a single sign-on mode with these three unrelated projects, plus the main page of the consolidated site, and there are four places to log in. Because the structure of the user Table is different, only one entry can be entered, the jump site will not be wrong, that is, in the Consolidated page login.

Now I want to take the ring win digital This site separate out, and the remaining two sites continue to achieve single sign-on, how to do? Or is my asp.net space is rented, the service provider certainly cannot let me revise machine.config, what do I do? "The way is people want to come out drop!!" According to the above Machine.config and Web.config relationship, we can put <machineKey> node in the project root directory web.config <system.web> node. As follows:

1, the Rights Management system project Web.config for Form authentication settings

<machinekey validationkey= "ad117f2f286cdcb15a9d1d4535e16db0248026939**author**cityhunter172****website**172* meibu*com****mailto**cityhunter172@126*com*****f2f286cdcb15a9d1d4535e16db0248026939 "decryptionKey=" 3c89ae62ad117f2f286cdcb15a9d1d4535e16db0248026939 "validation=" SHA1 "/>

<authentication mode= "Forms" >

<forms loginurl= "Login.aspx" name= "172.meibu.com_warrant" ></forms>

</authentication>

<authorization><deny users= "?" ></deny></authorization>

2, IT internal Management network project Web.config for Form certification settings

<machinekey validationkey= "ad117f2f286cdcb15a9d1d4535e16db0248026939**author**cityhunter172****website**172* meibu*com****mailto**cityhunter172@126*com*****f2f286cdcb15a9d1d4535e16db0248026939 "decryptionKey=" 3c89ae62ad117f2f286cdcb15a9d1d4535e16db0248026939 "validation=" SHA1 "/>

<authentication mode= "Forms" >

<forms loginurl= "Login.aspx" name= "172.meibu.com_it" ></forms>

</authentication>

<authorization><deny users= "?" ></deny></authorization>

We may be impatient to try, and I am in favour of such a practice, for the fact is the only way to test the truth. If you don't try to do it yourself, it's hard to see what I'm saying here. Don't worry, I already know what you want to say, listen to me slowly explain to you:

A two projects Web.cinfig <machineKey> nodes ensure that the following fields are exactly the same: ValidationKey, decryptionkey, validation

b The Cookie name for the two items must be the same, that is, the name attribute in <forms>, where we unify it as name = "172.meibu.com_project"

c) Note case sensitivity

In the process of integration, I have to say to the people of the problems encountered, lest you go the same way.

1 First, the user management should be the problem, the two users of the project integration, is not an easy thing, the principle is to create a new Table only to store the account number and password, with the account to do the association, write triggers, so that the synchronization between the Table;

2 do not expect two projects to be passed by the session to the value, two application sessions are not shared. Someone on the internet has put the class library (the compiled. dll document) into the same Bin folder to implement session sharing, this practice is to merge two projects into an application, not what we want, the reason is very simple: Sohu and Chinaren Server division between the two should do?

3 The transfer value between projects, can be implemented with cookies. In the first section of section III (http://blog.csdn.net/cityhunter172/archive/2005/11/06/524043.aspx) we introduced the only running System.Web.Security.FormsAuthentication.SetAuthCookie method to achieve login, the essence of a single sign-on is a Cookie containing the authentication ticket can be shared between projects.

Next, it is necessary to introduce the use of cookies in. Net.

12, the use of cookies in the ASP.net

Everyone may be the same as me, rarely use cookies in the ASP.net, pass the parameters, save variables Ah, with more than the session or ViewState and hidden controls, some simply use "? "The request way.

1, cookies stored in the directory

Cookies are stored in the client's Dongdong, placed in the "temporary Internet Files" directory, so there is a security problem. We can find the specific location in the following ways: Open the Control Panel →internet option → general →internet temporary files → set → You can see the "current position", → click "View File" will open the folder directly, you can also click "Mobile Folder" to change its location. Refer to the following figure:

2, the validity of the Cookie

From the above we can clearly see the "deadline" (that is, the expiration date) for each Cookie document. During the validity period, when the user who logs on to the computer accesses 172.meibu.com again, IE will request the page at the same time, along with the above name "Cookie:administrator@172.meibu.com" Cookie document content to the server.

If the document contains a value for multiple cookies, the cutoff period is the final expiration date.

3. Type of Cookie

Here we divide by the validity period, divides into two kinds:

A) Instant-type

The cookie is invalidated when the browser is closed (all IE browsing 172.meibu.com), and such cookies do not appear in the "temporary Internet Files" directory. In fact, it also has a cut-off period, for "0001-01-01"

b) Persistent type

Is the Cookie that has been specified as a specific "deadline" that can be found in the "temporary Internet Files" directory

4, the contents of the Cookie

Double-click to open "cookie:administrator@172.meibu.com" and we see the following figure below:


Above, "" is a line break, if you want to break any pot to ask me exactly how to know. I would be happy to tell you: this is experience! From the moment I learned C #, I took the first Windows program--Notepad to operate and save the document.

So the server read out the format as follows:


5. Issue cookies on asp.net page

The. CS code to send the above Cookie is:

System.Web.HttpCookie ck = new HttpCookie ("CkValue0");

ck["Author"] = "cityhunter";

Ck. Expires = System.DateTime.Now.AddMinutes (10);//If not specified, instant Cookie

Ck. Path= "/formtest/managesys"; Set the virtual path of the cookie, note that it must start with "/", otherwise an invalid cookie; Please take a look at it. Relationship to the cookie document "name" and "Internet address" in the guest room

RESPONSE.COOKIES.ADD (CK);



ck = new HttpCookie ("ckValue1"); Re-create a Cookie named CkValue1

Ck.   Expires = System.DateTime.Now.AddMinutes (20); 20 minutes to expire immediately.

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 issued Cookie

Response.Write (request.cookies["CkValue0"] ["Author"]+ "<br>");/no need to explain.

Response.Write (request.cookies["ckValue1"] ["E_Mail"]+ "<br>");

Response.Write (request.cookies["ckValue1"] ["personalweb"]);

I haven't had homework for a long time. , this third article Ah, but spent my two weeks of spare time debugging, summing up, writing, all said that time is golden, I do not know how much money I spent in exchange for how many silver? For silver, I see no hope, can get your comment, I also satisfied. Remember, your comment is the motivation that I continue to write.

Job: Assign the following value to the Cookie, and how to get its correct value

ck["str1"] = "2222";

ck["str"] = "str0=11111&str1=223";

It is certain that request.cookies["ckValue1" ["str"] can not get "str0=11111&str1=223" This string, you may wish to try request.cookies["ckValue1" [" STR1 "] will get an unexpected string yo.

Tip: Use Server.URLEncode () and Server.urldecode ()

13, issued a permanent verification Cookie

Finally...... Finally...... The last chapter, suddenly looking back, a voluminous 12 chapters. I did not expect to write the composition of the young, incredibly also can make up more than thousands of words of the article to Ah, have to admire my own Ah! Looking back, a large and faint person .... How far is it ever going to be? How long is it forever? Only God knows.

Do you notice when you log in Csdn a "2 weeks no longer login" checkbox, and how does it do it? Have you ever encountered such confusion: when the execution of System.Web.Security.FormsAuthentication.SetAuthCookie was clearly specified createPersistentCookie is true Why is it still not possible to close the browser directly to the Web? Here's a question for you to explain, and how to create the authentication ticket and add it to the Cookie manually.

System.Web.Security.FormsAuthenticationTicket tk = new System.Web.Security.FormsAuthenticationTicket (

1,//Specify version number: can be arbitrarily specified

"Admin",//Login username: corresponding to web.config <allow users= "admin" .../> users properties

System.DateTime.Now,//release time

System.DateTime.Now.AddYears (100),//Expiration Time: 100 years from now, it's never long enough.

False,//whether it is a persistent Cookie: No use has been found, at least for now I do not know, the following will be explained

"Test user Data"/user data: Available ((System.Web.Security.FormsIdentity) user.identity). Ticket.userdata get

);

String str = System.Web.Security.FormsAuthentication.Encrypt (TK);//Encrypted Identity ticket

Declare a Cookie named <forms name= in Web.config. Apsx ".../> 's Name property, corresponding to the value of the identity ticket after the encrypted string

System.Web.HttpCookie ck = new HttpCookie (SYSTEM.WEB.SECURITY.FORMSAUTHENTICATION.FORMSCOOKIENAME,STR);

Specifies that the Cookie is <forms path= "/" in Web.config .../> path property, not specified, default to "/"

Ck. Path=system.web.security.formsauthentication.formscookiepath;



This sentence is very important, less, even if the cookie is designated as a persistent cookie in the identity ticket, the instant cookie does not expire when it closes the browser; So I said, "I really don't know what it is to specify a persistent cookie in the identity ticket."

Ck. Expires = System.DateTime.Now.AddYears (100);

RESPONSE.COOKIES.ADD (CK); Add to guest room end


Postscript

This series of articles total three parts, lasted one months to complete (2005-11-05 ~ 2005-12-06). These are some of the experiences I have learned and used in practice, to share with you here. Code is debugged, if there is any doubt, can be found in the CSDN Forum (http://community.csdn.net/), my ID is cityhunter172 (use this ID send a short message to me), nickname for the cold feather maple, welcome to criticize correct.

Another, found that there are individual sites in the reprint of my article, not only deleted some of the content, the most intolerable is not marked the author, but did not find the source. In this, once again hope that you reprint, please be sure to indicate the author as "Cold Feather Maple (cityhunter172)", thank you.



Related Article

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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