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