C# HttpCookie.HttpOnly属性

  HttpCookie.HttpOnly属性获取或设置一个值,该值指定 Cookie 是否可通过客户端脚本访问。

命名空间:System.Web
程序集:System.Web(在 system.web.dll 中)
属性值:如果 Cookie 具有 HttpOnly 属性且不能通过客户端脚本访问,则为 true;否则为 false。默认为 false

备注

  Microsoft Internet Explorer 版本 6 Service Pack 1 和更高版本支持 Cookie 属性 HttpOnly, 该属性有助于缓解跨站点脚本威胁,这种威胁可能导致 Cookie 被窃取。窃取的 Cookie 可以包含标识站点用户的敏感信息,如 ASP.NET 会话 ID 或 Forms 身份验证票证,攻击者可以重播窃取的 Cookie,以便伪装成用户或获取敏感信息。如果兼容浏览器接收到 HttpOnly Cookie,则客户端脚本不能对它进行访问。

  警告:HttpOnly 属性设置为 true,并不能防止对网络频道具有访问权限的攻击者直接访问该 Cookie。针对这种情况,应考虑使用安全套接字层 (SSL) 来提供帮助。工作站的安全也很重要,原因是恶意用户可能使用打开的浏览器窗口或包含持久性 Cookie 的计算机,以合法用户的标识获取对网站的访问。

C#使用HttpCookie.HttpOnly属性示例

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        // Create a new HttpCookie.
        HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
        // By default, the HttpOnly property is set to false 
        // unless specified otherwise in configuration.
        myHttpCookie.Name = "MyHttpCookie";
        Response.AppendCookie(myHttpCookie);
        // Show the name of the cookie.
        Response.Write(myHttpCookie.Name);
        // Create an HttpOnly cookie.
        HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
        // Setting the HttpOnly value to true, makes
        // this cookie accessible only to ASP.NET.
        myHttpOnlyCookie.HttpOnly = true;
        myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
        Response.AppendCookie(myHttpOnlyCookie);
        // Show the name of the HttpOnly cookie.
        Response.Write(myHttpOnlyCookie.Name);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
<script type="text/javascript">
function getCookie(NameOfCookie)
{
    if (document.cookie.length > 0) 
{ 
    begin = document.cookie.indexOf(NameOfCookie+"="); 
    if (begin != -1)
   { 
    begin += NameOfCookie.length+1; 
      end = document.cookie.indexOf(";", begin);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(begin, end));       
      } 
  }
return null;  
}
</script>
<script type="text/javascript">
    // This code returns the cookie name.
    alert("Getting HTTP Cookie");
    alert(getCookie("MyHttpCookie"));
    // Because the cookie is set to HttpOnly,
    // this returns null.
    alert("Getting HTTP Only Cookie");
    alert(getCookie("MyHttpOnlyCookie"));
</script> 
</body>
</html>

来源:http://technet.microsoft.com/zh-cn/library/system.web.httpcookie.httponly%28en-us,VS.85%29.aspx

加支付宝好友偷能量挖...


评论(0)网络
阅读(1027)喜欢(0)Asp.Net/C#/WCF