Cookie 规范

INTRODUCTION

Cookiesareageneralmechanismwhichserversideconnections(suchasCGIscripts)canusetobothstoreandretrieveinformationontheclientsideoftheconnection.Theadditionofasimple,persistent,client-sidestatesignificantlyextendsthecapabilitiesofWeb-basedclient/serverapplications.

OVERVIEW

Aserver,whenreturninganHTTPobjecttoaclient,mayalsosendapieceofstateinformationwhichtheclientwillstore.IncludedinthatstateobjectisadescriptionoftherangeofURLsforwhichthatstateisvalid.AnyfutureHTTPrequestsmadebytheclientwhichfallinthatrangewillincludeatransmittalofthecurrentvalueofthestateobjectfromtheclientbacktotheserver.Thestateobjectiscalledacookie,fornocompellingreason.

Thissimplemechanismprovidesapowerfulnewtoolwhichenablesahostofnewtypesofapplicationstobewrittenforweb-basedenvironments.Shoppingapplicationscannowstoreinformationaboutthecurrentlyselecteditems,forfeeservicescansendbackregistrationinformationandfreetheclientfromretypingauser-idonnextconnection,sitescanstoreper-userpreferencesontheclient,andhavetheclientsupplythosepreferenceseverytimethatsiteisconnectedto.

SPECIFICATION

AcookieisintroducedtotheclientbyincludingaSet-CookieheaderaspartofanHTTPresponse,typicallythiswillbegeneratedbyaCGIscript.

SyntaxoftheSet-CookieHTTPResponseHeader

ThisistheformataCGIscriptwouldusetoaddtotheHTTPheadersanewpieceofdatawhichistobestoredbytheclientforlaterretrieval.

Set-Cookie:NAME=VALUE;expires=DATE;

path=PATH;domain=DOMAIN_NAME;secure

NAME=VALUE

Thisstringisasequenceofcharactersexcludingsemi-colon,commaandwhitespace.Ifthereisaneedtoplacesuchdatainthenameorvalue,someencodingmethodsuchasURLstyle%XXencodingisrecommended,thoughnoencodingisdefinedorrequired.

ThisistheonlyrequiredattributeontheSet-Cookieheader.

expires=DATE

Theexpiresattributespecifiesadatestringthatdefinesthevalidlifetimeofthatcookie.Oncetheexpirationdatehasbeenreached,thecookiewillnolongerbestoredorgivenout.

Thedatestringisformattedas:

Wdy,DD-Mon-YYYYHH:MM:SSGMT

ThisisbasedonRFC822,RFC850,RFC1036,andRFC1123,withthevariationsthattheonlylegaltimezoneisGMTandtheseparatorsbetweentheelementsofthedatemustbedashes.

expiresisanoptionalattribute.Ifnotspecified,thecookiewillexpirewhentheuser'ssessionends.

Note:ThereisabuginNetscapeNavigatorversion1.1andearlier.Onlycookieswhosepathattributeissetexplicitlyto"/"willbeproperlysavedbetweensessionsiftheyhaveanexpiresattribute.

domain=DOMAIN_NAME

Whensearchingthecookielistforvalidcookies,acomparisonofthedomainattributesofthecookieismadewiththeInternetdomainnameofthehostfromwhichtheURLwillbefetched.Ifthereisatailmatch,thenthecookiewillgothroughpathmatchingtoseeifitshouldbesent."Tailmatching"meansthatdomainattributeismatchedagainstthetailofthefullyqualifieddomainnameofthehost.Adomainattributeof"acme.com"wouldmatchhostnames"anvil.acme.com"aswellas"shipping.crate.acme.com".

Onlyhostswithinthespecifieddomaincansetacookieforadomainanddomainsmusthaveatleasttwo(2)orthree(3)periodsinthemtopreventdomainsoftheform:".com",".edu",and"va.us".Anydomainthatfailswithinoneofthesevenspecialtopleveldomainslistedbelowonlyrequiretwoperiods.Anyotherdomainrequiresatleastthree.Thesevenspecialtopleveldomainsare:"COM","EDU","NET","ORG","GOV","MIL",and"INT".

Thedefaultvalueofdomainisthehostnameoftheserverwhichgeneratedthecookieresponse.

path=PATH

ThepathattributeisusedtospecifythesubsetofURLsinadomainforwhichthecookieisvalid.Ifacookiehasalreadypasseddomainmatching,thenthepathnamecomponentoftheURLiscomparedwiththepathattribute,andifthereisamatch,thecookieisconsideredvalidandissentalongwiththeURLrequest.Thepath"/foo"wouldmatch"/foobar"and"/foo/bar.html".Thepath"/"isthemostgeneralpath.

Ifthepathisnotspecified,itasassumedtobethesamepathasthedocumentbeingdescribedbytheheaderwhichcontainsthecookie.

secure

Ifacookieismarkedsecure,itwillonlybetransmittedifthecommunicationschannelwiththehostisasecureone.CurrentlythismeansthatsecurecookieswillonlybesenttoHTTPS(HTTPoverSSL)servers.

Ifsecureisnotspecified,acookieisconsideredsafetobesentintheclearoverunsecuredchannels.

SyntaxoftheCookieHTTPRequestHeader

WhenrequestingaURLfromanHTTPserver,thebrowserwillmatchtheURLagainstallcookiesandifanyofthemmatch,alinecontainingthename/valuepairsofallmatchingcookieswillbeincludedintheHTTPrequest.Hereistheformatofthatline:

Cookie:NAME1=OPAQUE_STRING1;NAME2=OPAQUE_STRING2...

AdditionalNotes

MultipleSet-Cookieheaderscanbeissuedinasingleserverresponse.

Instancesofthesamepathandnamewilloverwriteeachother,withthelatestinstancetakingprecedence.Instancesofthesamepathbutdifferentnameswilladdadditionalmappings.

Settingthepathtoahigher-levelvaluedoesnotoverrideothermorespecificpathmappings.Iftherearemultiplematchesforagivencookiename,butwithseparatepaths,allthematchingcookieswillbesent.(Seeexamplesbelow.)

Theexpiresheaderletstheclientknowwhenitissafetopurgethemappingbuttheclientisnotrequiredtodoso.Aclientmayalsodeleteacookiebeforeit'sexpirationdatearrivesifthenumberofcookiesexceedsitsinternallimits.

Whensendingcookiestoaserver,allcookieswithamorespecificpathmappingshouldbesentbeforecookieswithlessspecificpathmappings.Forexample,acookie"name1=foo"withapathmappingof"/"shouldbesentafteracookie"name1=foo2"withapathmappingof"/bar"iftheyarebothtobesent.

Therearelimitationsonthenumberofcookiesthataclientcanstoreatanyonetime.Thisisaspecificationoftheminimumnumberofcookiesthataclientshouldbepreparedtoreceiveandstore.

300totalcookies

4kilobytespercookie,wherethenameandtheOPAQUE_STRINGcombinetoformthe4kilobytelimit.

20cookiesperserverordomain.(notethatcompletelyspecifiedhostsanddomainsaretreatedasseparateentitiesandhavea20cookielimitationforeach,notcombined)

Serversshouldnotexpectclientstobeabletoexceedtheselimits.Whenthe300cookielimitorthe20cookieperserverlimitisexceeded,clientsshoulddeletetheleastrecentlyusedcookie.Whenacookielargerthan4kilobytesisencounteredthecookieshouldbetrimmedtofit,butthenameshouldremainintactaslongasitislessthan4kilobytes.

IfaCGIscriptwishestodeleteacookie,itcandosobyreturningacookiewiththesamename,andanexpirestimewhichisinthepast.Thepathandnamemustmatchexactlyinorderfortheexpiringcookietoreplacethevalidcookie.Thisrequirementmakesitdifficultforanyonebuttheoriginatorofacookietodeleteacookie.

WhencachingHTTP,asaproxyservermightdo,theSet-cookieresponseheadershouldneverbecached.

IfaproxyserverreceivesaresponsewhichcontainsaSet-cookieheader,itshouldpropagatetheSet-cookieheadertotheclient,regardlessofwhethertheresponsewas304(NotModified)or200(OK).

Similarly,ifaclientrequestcontainsaCookie:header,itshouldbeforwardedthroughaproxy,eveniftheconditionalIf-modified-sincerequestisbeingmade.

EXAMPLES

Herearesomesampleexchangeswhicharedesignedtoillustratetheuseofcookies.

FirstExampletransactionsequence:

Clientrequestsadocument,andreceivesintheresponse:

Set-Cookie:CUSTOMER=WILE_E_COYOTE;path=/;expires=Wednesday,09-Nov-9923:12:40GMT

WhenclientrequestsaURLinpath"/"onthisserver,itsends:

Cookie:CUSTOMER=WILE_E_COYOTE

Clientrequestsadocument,andreceivesintheresponse:

Set-Cookie:PART_NUMBER=ROCKET_LAUNCHER_0001;path=/

WhenclientrequestsaURLinpath"/"onthisserver,itsends:

Cookie:CUSTOMER=WILE_E_COYOTE;PART_NUMBER=ROCKET_LAUNCHER_0001

Clientreceives:

Set-Cookie:SHIPPING=FEDEX;path=/foo

WhenclientrequestsaURLinpath"/"onthisserver,itsends:

Cookie:CUSTOMER=WILE_E_COYOTE;PART_NUMBER=ROCKET_LAUNCHER_0001

WhenclientrequestsaURLinpath"/foo"onthisserver,itsends:

Cookie:CUSTOMER=WILE_E_COYOTE;PART_NUMBER=ROCKET_LAUNCHER_0001;SHIPPING=FEDEX

SecondExampletransactionsequence:

Assumeallmappingsfromabovehavebeencleared.

Clientreceives:

Set-Cookie:PART_NUMBER=ROCKET_LAUNCHER_0001;path=/

WhenclientrequestsaURLinpath"/"onthisserver,itsends:

Cookie:PART_NUMBER=ROCKET_LAUNCHER_0001

Clientreceives:

Set-Cookie:PART_NUMBER=RIDING_ROCKET_0023;path=/ammo

WhenclientrequestsaURLinpath"/ammo"onthisserver,itsends:

Cookie:PART_NUMBER=RIDING_ROCKET_0023;PART_NUMBER=ROCKET_LAUNCHER_0001

NOTE:Therearetwoname/valuepairsnamed"PART_NUMBER"duetotheinheritanceofthe"/"mappinginadditiontothe"/ammo"mapping.

相关推荐