Http Cookie里面HttpOnly和Secure标记

Secure

The secure option is a flag that can be set by the application server when sending a new cookie to the user within a HTTP Response. The purpose of the secure flag is to prevent cookie from be observed by an unauthorized party due to the transmission of a cookie in clear text. (不管网站是https还是http,代码里面都可以设置cookie的secure flag,这个是服务器端的行为。能不能传输带有secure flag的cookie,取决于客户端浏览器。)

To accomplish this goal, browsers which support the secure flag will only send cookies with the secure flag when the request is going to a HTTPS page. Said in another way, browser will not send a cookie with the secure flag set over an unencryped HTTP request.

Browser define whether the HTTP request is encryped. (一般来说,https开头的url都是被browser认可的加密过的安全通道,这样的通道可以传输带有secure标记的cookie,但是也有一些特殊情况,例如Chrome不认为SHA-1签名的证书是安全的,所以即使url是https开头的,Chrome也不会传输带有secure标记的cookie。)

C# .NET example:

HttpCookie cookie = new HttpCookie("UID");
cookie.Path = "/";
cookie.Value = loginId.ToLower();
cookie.Expires = DateTime.Now.AddDays(1);
cookie.Secure = true;
Response.Cookies.Add(cookie);

HttpOnly

HttpOnly cookies were first implemented in 2002 by Microsoft Internet Explorer developers for IE 6 SP1. If the HttpOnly flag is included in the HTTP response header, the client cannot access the cookie through client side script (if client browser supports this flag.)

How to Remove Cookie?

You cannot directly remove a cookie from client's browser. However, you can direct the user's browser to remove the cookie by setting the expiration date of the cookie to a past date. The next time a user make a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.

C# .NET example:

if (Request.Cookies["UserSettings"] != null)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1);
    Response.Cookies.Add(myCookie);
}

 

参考链接:

https://www.owasp.org/index.php/SecureFlag

https://www.owasp.org/index.php/HttpOnly

https://msdn.microsoft.com/en-us/library/ms178195(v=vs.100).aspx

posted @ 2016-11-02 13:19  liangzi4000  阅读(11036)  评论(0编辑  收藏  举报