ASP.NET MVC C#应用HTTPCookie安全存储问题咨询与改造方案
问题1 现有实现的安全性确认
你当前的Cookie处理逻辑没有做任何加密防护,所有人都可以直接查看原始内容:
- 你看到的十六进制格式仅为
HttpUtility.UrlEncode的编码结果,作用是兼容Cookie对特殊字符的存储限制,不属于加密机制,只需要用任意UrlDecode工具就能100%还原原始内容 - 代码中注释掉的
HttpSecureCookie.Decode才是ASP.NET官方提供的安全Cookie解密逻辑,你当前未启用该逻辑,所以Cookie值本质就是明文编码后存储,用户打开浏览器F12的存储面板就能直接查看,甚至可以自行篡改内容后提交到服务器,服务端无法识别篡改行为
问题2 加密存储修改方案
推荐优先使用ASP.NET内置的HttpSecureCookie机制实现加密,不需要自行实现加密逻辑,安全性由框架保障,修改成本极低。
第一步 修改CookieStore类代码
using System; using System.Web; using System.Web.Security; // 需引入该命名空间,HttpSecureCookie在此命名空间下 namespace My.Application.Sample { public class CookieStore { public static void SetCookie(string key, string value) { SetCookie(key, value, TimeSpan.FromDays(14)); } public static void SetCookie(string key, string value, TimeSpan expires) { HttpCookie cookie = new HttpCookie(key, value); // 对Cookie进行加密,同时自带篡改校验能力 cookie = HttpSecureCookie.Encode(cookie); // 补充安全属性,进一步提升安全性 cookie.HttpOnly = true; // 禁止前端JS读取,防范XSS窃取Cookie cookie.Secure = HttpContext.Current.Request.IsSecureConnection; // HTTPS环境下仅通过HTTPS传输 cookie.SameSite = SameSiteMode.Lax; // 防范CSRF攻击 cookie.Expires = DateTime.Now.Add(expires); if (HttpContext.Current.Request.Cookies[key] != null) { HttpContext.Current.Response.Cookies.Set(cookie); } else { HttpContext.Current.Response.Cookies.Add(cookie); } } /// <summary> /// 根据指定key返回Cookie存储的值,不存在则返回空字符串 /// </summary> /// <param name="key"></param> /// <returns> 永远不会返回null :) </returns> public static string GetCookie(string key) { string value = string.Empty; try { HttpCookie cookie = HttpContext.Current.Request.Cookies[key]; if (cookie != null) { // 解密Cookie,内容被篡改会自动抛出异常 HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie); value = decodedCookie.Value; } } catch (Exception) { // 解密失败代表Cookie被篡改或已失效,直接返回空即可 } return value; } } }
第二步 配置machineKey(多服务器部署必填)
如果你的站点是多服务器部署,需要在web.config的system.web节点下配置统一的machineKey,保证不同服务器加密解密结果一致:
<system.web> <machineKey validationKey="自行生成的32位以上随机字符串" decryptionKey="自行生成的16位以上随机字符串" validation="SHA1" decryption="AES" /> <!-- 其余原有配置 --> </system.web>
单服务器部署的话框架会自动生成machineKey,不需要额外配置。
额外注意事项
- 即使加密后也不建议在Cookie中存储密码、身份证号等高度敏感信息,购物车非敏感数据可正常存储
- 生产环境建议全站启用HTTPS,配合
Secure属性避免Cookie在传输过程中被窃取
内容的提问来源于stack exchange,提问作者VSB
相关产品推荐
相关产品推荐

