djang set_signed_cookie 理解
signed_cookie 只是加了簽名的 cookie, 而不是被加密的 cookie.
signed_cookie 的作用是防止用戶私自纂改.參考: Securing Web Cookies With Signatures
So once I’ve logged in, we set a username cookie containing “Michael Brunton-Spall”, or uid=1 or something.
The problem with this is that the user is in total control of this cookie
單純的記錄 uid 或者用戶名在 cookie 中很容易被篡改(也是不建議將用戶敏感信息記錄在cookie中的原因), 萬一攻擊者把uid=1換成uid=2豈不是可以訪問 uid=2用戶的資源了嗎? 而如果換成uid=2:1fPjh2:iQGDDYNcgSYkIFqa2ixqakj6-gI那么服務端不僅檢驗uid, 還檢驗uid=2后面的簽名字段, 即是調用HttpRequest.get_signed_cookie(key=key, salt=salt), 這樣即使用戶把 cookie 中的 value 換成 uid=2, 但是沒有簽名, 服務端照樣拒絕訪問資源.
另外, Django 的 cookie 簽名是用的Base64_with_hmac, 參考: Source code for django.core.signing
如果需要在 cookie 里設置被加密的 value, 需要自行對 value 進行加密(好像只能是對稱加密), 比如使用hashlib.sha256{參考: hashlib — Secure hashes and message digests}:
cookie簽名代碼:
response.set_signed_cookie("qyUserName", "WANGCONGXING", salt="d8s#wc%0t7")
設置cookie后的效果: