萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP Cookies 完整操作指南:建立、讀取、字典、屬性與安全性

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"))
%>

安全性最佳實務

  1. 敏感資料勿存 Cookie:SessionID、Token 應存在 Session/資料庫,Cookie 僅存識別碼
  2. 啟用 Secure + HttpOnly:防止竊聽與 XSS 竊取
  3. 設定 SameSite=Lax/Strict:防禦 CSRF 攻擊
  4. 簽名驗證:重要 Cookie 加入 HMAC 簽名防竄改
  5. 定期輪換:敏感 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(複雜,不建議)
%>
copyright © 萬盛學電腦網 all rights reserved