萬盛學電腦網

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

ASP Cookie 進階操作:Domain、Path、HasKeys、Secure 屬性實戰

ASP Cookie 進階屬性與字典操作:跨域共享、路徑隔離與安全強化

Cookie 的 Domain、Path、Secure、HasKeys 等屬性決定了 Cookie 的可見範圍與安全性。本文透過實戰場景詳細說明各屬性運作機制與配置策略。

Domain 屬性:跨子域共享

<%
' 場景:主站 example.com,子站 shop.example.com、api.example.com 共享登入狀態

' ❌ 錯誤:設定完整網址
Response.Cookies("auth").Domain = "https://www.example.com"  ' 無效!

' ✅ 正確:設定根網域(前綴點號可選,現代瀏覽器兩者皆支援)
Response.Cookies("auth").Domain = ".example.com"   ' 含所有子域
' 或
Response.Cookies("auth").Domain = "example.com"    ' 同樣效果

' 限制:無法跨不同根網域(example.com → another.com)
%>

Path 屬性:路徑隔離

<%
' 場景:/admin/ 後台獨立 Cookie,/api/ API 專用 Token,前台共用

' 後台管理 Cookie(僅 /admin/ 路徑可見)
Response.Cookies("admin_session")("user_id") = 1001
Response.Cookies("admin_session").Path = "/admin/"
Response.Cookies("admin_session").Secure = True

' API Token(僅 /api/ 路徑可見)
Response.Cookies("api_token").Path = "/api/"
Response.Cookies("api_token").Secure = True
Response.Cookies("api_token").HttpOnly = True  ' 需 IIS 設定

' 前台通用 Cookie(全站可見)
Response.Cookies("frontend_pref").Path = "/"
Response.Cookies("frontend_pref")("theme") = "dark"

' ⚠️ 注意:Path 區分大小寫(依瀏覽器實作),建議統一小寫
%>

HasKeys:檢測字典型 Cookie

<%
' 判斷 Cookie 是單值還是字典
Dim cookieName
For Each cookieName In Request.Cookies
    If Request.Cookies(cookieName).HasKeys Then
        Response.Write cookieName & " 是字典型 Cookie
" Dim key For Each key In Request.Cookies(cookieName) Response.Write "  " & key & " = " & Request.Cookies(cookieName)(key) & "
" Next Else Response.Write cookieName & " = " & Request.Cookies(cookieName) & " (單值)
" End If Next ' 實務:遷移舊單值 Cookie 為字典 If Not Request.Cookies("user_prefs").HasKeys Then ' 舊版單值,遷移為字典 Dim oldVal : oldVal = Request.Cookies("user_prefs") Response.Cookies("user_prefs")("legacy") = oldVal Response.Cookies("user_prefs")("theme") = "light" Response.Cookies("user_prefs").Expires = DateAdd("d", 365, Now()) End If %>

Secure 屬性:僅 HTTPS 傳輸

<%
' 生產環境強制啟用
Response.Cookies("auth_token").Secure = True

' 開發環境 HTTP 下 Secure=True 會導致 Cookie 不被發送
' 解決:根據 Request.ServerVariables("HTTPS") 動態設定
Dim isHTTPS
isHTTPS = (LCase(Request.ServerVariables("HTTPS")) = "on")

Response.Cookies("auth_token").Secure = isHTTPS

' 或統一在包含檔設定
' Const COOKIE_SECURE = True  ' 生產環境設 True
%>

完整屬性設定範本

<%
Sub SetSecureCookie(name, value, expiresDays, path, domain, isDictionary)
    Dim dictMode : dictMode = CBool(isDictionary)
    
    If dictMode Then
        ' 假設 value 為 Dictionary 物件
        Dim key
        For Each key In value.Keys
            Response.Cookies(name)(key) = value(key)
        Next
    Else
        Response.Cookies(name) = value
    End If
    
    ' 通用屬性
    If expiresDays > 0 Then
        Response.Cookies(name).Expires = DateAdd("d", expiresDays, Now())
    End If
    
    If path <> "" Then Response.Cookies(name).Path = path
    If domain <> "" Then Response.Cookies(name).Domain = domain
    
    ' 安全屬性(生產環境必開)
    Response.Cookies(name).Secure = (LCase(Request.ServerVariables("HTTPS")) = "on")
    ' HttpOnly 需 IIS 設定,此處標記供前端/中間件參考
    ' Response.Cookies(name)("HttpOnly") = "True"  ' 非標準,僅作記錄
End Sub

' 使用範例
Dim userDict : Set userDict = Server.CreateObject("Scripting.Dictionary")
userDict("id") = "12345"
userDict("name") = "John"
userDict("role") = "admin"
Call SetSecureCookie("auth", userDict, 7, "/", ".example.com", True)
%>

Cookie 完整生命週期管理

<%
Class CookieManager
    Private defaultPath, defaultDomain, defaultSecure
    
    Private Sub Class_Initialize()
        defaultPath = "/"
        defaultDomain = ".example.com"
        defaultSecure = (LCase(Request.ServerVariables("HTTPS")) = "on")
    End Sub
    
    Public Sub SetValue(name, value, expiresDays)
        Response.Cookies(name) = value
        Response.Cookies(name).Path = defaultPath
        Response.Cookies(name).Domain = defaultDomain
        Response.Cookies(name).Secure = defaultSecure
        If expiresDays > 0 Then Response.Cookies(name).Expires = DateAdd("d", expiresDays, Now())
    End Sub
    
    Public Sub SetDict(name, dictObj, expiresDays)
        Dim key
        For Each key In dictObj.Keys
            Response.Cookies(name)(key) = dictObj(key)
        Next
        Response.Cookies(name).Path = defaultPath
        Response.Cookies(name).Domain = defaultDomain
        Response.Cookies(name).Secure = defaultSecure
        If expiresDays > 0 Then Response.Cookies(name).Expires = DateAdd("d", expiresDays, Now())
    End Sub
    
    Public Function GetValue(name, defaultVal)
        Dim val : val = Request.Cookies(name)
        If val = "" Then val = defaultVal
        GetValue = val
    End Function
    
    Public Function GetDict(name)
        Dim dict : Set dict = Server.CreateObject("Scripting.Dictionary")
        If Request.Cookies(name).HasKeys Then
            Dim key
            For Each key In Request.Cookies(name)
                dict(key) = Request.Cookies(name)(key)
            Next
        End If
        Set GetDict = dict
    End Function
    
    Public Sub Delete(name)
        Response.Cookies(name).Expires = DateAdd("d", -1, Now())
        Response.Cookies(name).Path = defaultPath
        Response.Cookies(name).Domain = defaultDomain
    End Sub
End Class

' 使用
Dim cookieMgr : Set cookieMgr = New CookieManager
cookieMgr.SetValue "lang", "zh-TW", 365
Dim prefs : Set prefs = cookieMgr.GetDict("user_prefs")
%>

跨域場景實戰:單點登入 (SSO) Cookie 策略

<%
' 主域:sso.example.com 統一認證
' 子應用:app1.example.com, app2.example.com

' 登入成功時(在 sso.example.com)
Response.Cookies("sso_token") = GenerateJWT(userData)
Response.Cookies("sso_token").Domain = ".example.com"
Response.Cookies("sso_token").Path = "/"
Response.Cookies("sso_token").Secure = True
Response.Cookies("sso_token").Expires = DateAdd("h", 2, Now())

' 子應用驗證(在 app1.example.com)
Dim token : token = Request.Cookies("sso_token")
If token <> "" Then
    Dim userData : userData = ValidateJWT(token)
    If IsObject(userData) Then
        ' 登入成功,建立本地 Session
        Session("UserID") = userData("user_id")
        Session("UserName") = userData("username")
    Else
        ' Token 無效,導向 SSO 登入
        Response.Redirect "https://sso.example.com/login?return_url=" & Server.URLEncode(Request.URL)
    End If
Else
    Response.Redirect "https://sso.example.com/login?return_url=" & Server.URLEncode(Request.URL)
End If
%>
copyright © 萬盛學電腦網 all rights reserved