您当前的位置:首页 > 建站知识 > 编程知识

Cookie的httponly属性设置方法

发布时间: 2014-05-08 │ 浏览:3752 

为了解决XSS(跨站脚本攻击)的问题,从IE6开始支持cookie的HttpOnly属性,这个属性目前已被大多数浏览器(IE、FF、Chrome、Safari)

所支持。当cookie中的HttpOnly属性被设置为true时,前端脚本JavaScript就无法访问或操作cookie了(只能通过后台访问),这样XSS就失效了。

即便是这样,也不要将重要信息存入cookie。


PHP设置方法:

header("Set-Cookie:tmp=100;HttpOnly");
或者
setcookie("tmp", 100, NULL, NULL, NULL, NULL, TRUE);


asp.net的设置方法:
HttpCookie myHttpCookie = new HttpCookie("LastVisit","test");
myHttpOnlyCookie.HttpOnly = true;
Response.AppendCookie(myHttpOnlyCookie);

 

ASP的内置对象中没有提供相关方法,只能变通来实现了:
 
‘———-SetHttpOnlyCookie—————————————-
‘功能:设置HttpOnly Cookie
‘参数:expDate 为保到期, 0表示不设置,设置为过去某一时间表示清除
‘参数:domain 为空(string.Empty)表示不设置
‘——————————————————————-
Function SetHttpOnlyCookie(cookieName,cookieValue,domain,path,expDate)
Dim cookie
cookie=cookieName & “=” & Server.URLEncode(cookieValue) & “; path=” & path
If expDate <> 0 Then
cookie=cookie & “; expires=” & DateToGMT(expDate)
End If
 
If domain <> “” Then
cookie=cookie & “; domain=” & domain
End If
 
cookie=cookie & “; HttpOnly”
 
Call Response.AddHeader (”Set-Cookie”, cookie)
End Function
 
‘————-getGMTTime————
‘参数: sDate 需要转换成GMT的时间
‘———————————
Function DateToGMT(sDate)
Dim dWeek,dMonth
Dim strZero,strZone
strZero=”00″
strZone=”+0800″
dWeek=Array(”Sun”,”Mon”,”Tue”,”Wes”,”Thu”,”Fri”,”Sat”)
dMonth=Array(”Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jul”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”)
DateToGMT = dWeek(WeekDay(sDate)-1)&”, “&Right(strZero&Day(sDate),2)&” “&dMonth(Month(sDate)-1)&” “&Year(sDate)&” “&Right(strZero&Hour(sDate),2)&”:”&Right(strZero&Minute(sDate),2)&”:”&Right(strZero&Second(sDate),2)&” “&strZone
End Function
‘参考
‘Call SetHttpOnlyCookie(”cookieOnly1″,”onlyValue”,”.gyzs.com”,”/”,0)