ASP Cookie 全方位掌握:從基礎操作到安全最佳實踐
Cookie 是 HTTP 無狀態協議中維持狀態的關鍵機制。本文完整涵蓋 ASP 中 Cookie 的建立、讀取、字典模式、屬性設定、安全性考量與現代替代方案。
基本操作:建立與讀取
<%
' 建立簡單 Cookie(必須在 標籤之前,或開啟 Response.Buffer = True)
Response.Cookies("username") = "john_doe"
' 設定屬性
Response.Cookies("username").Expires = DateAdd("d", 30, Now()) ' 30 天有效
Response.Cookies("username").Domain = "example.com" ' 跨子域共享
Response.Cookies("username").Path = "/" # 整個網站可用
Response.Cookies("username").Secure = True # 僅 HTTPS 傳輸
Response.Cookies("username").HttpOnly = True # 防 XSS(ASP 經典不直接支援,需 IIS 設定)
' 讀取
Dim username
username = Request.Cookies("username")
If username <> "" Then
Response.Write "歡迎回來," & username
End If
%>
Cookie 字典:單一 Cookie 儲存多值
<%
' 建立字典型 Cookie
Response.Cookies("user")("name") = "John Doe"
Response.Cookies("user")("email") = "john@example.com"
Response.Cookies("user")("role") = "admin"
Response.Cookies("user").Expires = DateAdd("d", 7, Now())
' 讀取字典值
Dim userName, userEmail
userName = Request.Cookies("user")("name")
userEmail = Request.Cookies("user")("email")
' 遍歷字典
Dim key
For Each key In Request.Cookies("user")
Response.Write key & " = " & Request.Cookies("user")(key) & "
"
Next
' 檢查是否為字典
If Request.Cookies("user").HasKeys Then
Response.Write "這是字典型 Cookie"
End If
%>
刪除 Cookie:設定過期時間為過去
<%
' 方法一:設定過去日期
Response.Cookies("username").Expires = DateAdd("d", -1, Now())
' 方法二:設定為空值並過期
Response.Cookies("user")("name") = ""
Response.Cookies("user").Expires = DateAdd("d", -1, Now())
' 刪除整個字典 Cookie
Response.Cookies("user").Expires = DateAdd("d", -1, Now())
%>
完整屬性參考表
| 屬性 | 說明 | 範例 | 必要性 |
Expires | 過期日期時間 | DateAdd("d", 30, Now()) | 持久化 Cookie 必須 |
Domain | 適用網域 | .example.com(含子域) | 跨子域共享 |
Path | 適用路徑 | /(全站)、/admin/ | 路徑隔離 |
Secure | 僅 HTTPS 傳送 | True | 生產環境必須 |
HttpOnly | 禁止 JavaScript 存取 | 需 IIS 設定或 URL Rewrite | 防 XSS 關鍵 |
SameSite | 跨站請求攜帶策略 | Strict/Lax/None | 防 CSRF(需 IIS 10+ / URL Rewrite) |
編碼與特殊字元處理
<%
' Cookie 值不支援分號、逗號、等號、空白,需編碼
Dim rawValue, encodedValue
rawValue = "用戶,資料;含有=特殊字元"
' 簡易編碼:URLEncode
encodedValue = Server.URLEncode(rawValue)
Response.Cookies("data") = encodedValue
' 讀取時解碼
Dim decodedValue
decodedValue = Server.URLDecode(Request.Cookies("data"))
%>
安全性最佳實務
- 敏感資料勿存 Cookie:SessionID、Token 應存在 Session/資料庫,Cookie 僅存識別碼
- 啟用 Secure + HttpOnly:防止竊聽與 XSS 竊取
- 設定 SameSite=Lax/Strict:防禦 CSRF 攻擊
- 簽名驗證:重要 Cookie 加入 HMAC 簽名防竄改
- 定期輪換:敏感 Cookie 設定較短過期時間
簽名 Cookie 實作範例
<%
Const SECRET_KEY = "your-256-bit-secret-key-here"
Function SignCookie(value)
Dim hmac : Set hmac = Server.CreateObject("System.Security.Cryptography.HMACSHA256")
' ASP 經典無內建 HMAC,需 COM 元件或改用 ASP.NET/其他語言
' 簡易替代:MD5(value & SECRET) - 僅示範概念,生產環境勿用
SignCookie = value & "|" & GetMD5Hash(value & SECRET_KEY)
End Function
Function VerifyCookie(signedValue)
Dim parts, value, signature, expectedSig
parts = Split(signedValue, "|")
If UBound(parts) <> 1 Then VerifyCookie = "" : Exit Function
value = parts(0)
signature = parts(1)
expectedSig = GetMD5Hash(value & SECRET_KEY)
If StrComp(signature, expectedSig, 0) = 0 Then
VerifyCookie = value
Else
VerifyCookie = "" ' 簽名驗證失敗
End If
End Function
' 使用
Response.Cookies("secure_data") = SignCookie("sensitive-value")
Dim verified : verified = VerifyCookie(Request.Cookies("secure_data"))
If verified = "" Then Response.Write "Cookie 已被竄改!"
%>
現代替代方案比較
| 方案 | 儲存位置 | 容量 | 自動攜帶 | 安全性 | 適用場景 |
| Cookie | 瀏覽器 | 4KB | 是(每請求) | 中 | 識別碼、偏好設定、追蹤 |
| Session | 伺服器記憶體/資料庫 | 無限制 | 透過 SessionID Cookie | 高 | 使用者狀態、購物車、權限 |
| LocalStorage | 瀏覽器 | 5-10MB | 否(需 JS 手動送出) | 中 | 大量客戶端資料、離線快取 |
| IndexedDB | 瀏覽器 | 數百 MB | 否 | 高 | 複雜客戶端應用 |
| JWT (Token) | 客戶端/Header | 視大小 | 手動 Authorization Header | 高(簽名驗證) | API 認證、無狀態架構 |
ASP 經典 Session 運作機制補充
<%
' Session 實際上靠 Cookie 傳遞 SessionID
' ASP 預設 Cookie 名:ASPSESSIONIDxxxxxxxx
' 設定 Session 逾時(分鐘)
Session.Timeout = 30
' 放棄 Session
Session.Abandon
' 關鍵:Session 依賴 Cookie,若用戶關閉 Cookie,Session 失效
' 解決:URL 重寫帶 SessionID(複雜,不建議)
%>