Definite guide to valid Cookie values

前端 未结 2 1457
失恋的感觉
失恋的感觉 2020-12-29 13:51

I know there are other questions but they seem to have answers which are assumptions rather than being definitive.

My limited understanding is that cookie values are

2条回答
  •  -上瘾入骨i
    2020-12-29 14:27

    The latest RFC is 6265, and it states that previous Cookie RFCs are obsoleted.

    Here's what the syntax rules in the RFC say:

     cookie-pair       = cookie-name "=" cookie-value
     cookie-name       = token
     cookie-value      = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
     cookie-octet      = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
                           ; US-ASCII characters excluding CTLs,
                           ; whitespace DQUOTE, comma, semicolon,
                           ; and backslash
    

    Thus:

    • The special characters are white-space characters, double quote, comma, semicolon and backslash. Equals is not a special character.

    • The special characters cannot be used at all, with the exception that double quotes may surround the value.

    • Special characters cannot be quoted.

    • Backslash does not act as an escape.

    It follows that base-64 encoding can be used, because equals is not special.

    Finally, from what I can tell, the RFC 6265 cookie values are defined so that they will work with any browser that implements any of the Cookie RFCs. However, if you tried to use cookie values that don't conform to RFC 6265 (but do arguably do conform to earlier RFCs), you may find that cookie behavior varies with different browsers.

    In short, conform to the letter of RFC 6265 and you should be fine.

    If you need pass cookie values that include any of the forbidden characters, your application needs to do its own encoding and decoding of the values; e.g. using base64.

提交回复
热议问题