乐闻世界logo
搜索文章和话题

What are the security attributes of Cookies? How to prevent Cookies from being stolen?

3月7日 11:43

Cookie security attributes include Secure, HttpOnly, SameSite, and Domain/Path restrictions, which are crucial for preventing Cookie theft or abuse.

Secure flag

  • Can only be transmitted over HTTPS protocol
  • Prevents leakage over unencrypted connections
  • Example: Set-Cookie: token=xyz; Secure

HttpOnly flag

  • Prevents JavaScript access via document.cookie
  • Prevents XSS attacks from stealing Cookies
  • Example: Set-Cookie: sessionId=abc; HttpOnly

SameSite attribute

  • Controls whether Cookies are sent during cross-site requests
  • Values: Strict (strict mode), Lax (relaxed mode), None (allow cross-site)
  • Prevents CSRF attacks
  • Example: Set-Cookie: token=xyz; SameSite=Strict

Domain and Path restrictions

  • Domain: specifies the valid domain for the Cookie
  • Path: specifies the valid path for the Cookie
  • Limits the scope of the Cookie
  • Example: Set-Cookie: token=xyz; Domain=.example.com; Path=/api

Best practices:

  • Sensitive Cookies must have Secure and HttpOnly set
  • Use SameSite=Lax or Strict to prevent CSRF
  • Set reasonable Domain and Path scopes
  • Regularly update Cookie expiration times
标签:Cookie