Http Cookie里面HttpOnly和Secure标记

本文详细介绍了安全Cookie的概念,包括secure flag和HttpOnly标志的作用及其设置方式。secure flag确保Cookie仅通过HTTPS传输,防止未授权访问;而HttpOnly标志则阻止客户端脚本访问Cookie,提升安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/liangzi4000/p/6022442.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值