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

What is SameSite Cookie? How does it prevent CSRF attacks?

3月6日 21:29

The SameSite Cookie attribute is used to control whether Cookies are sent during cross-site requests, and is an important security mechanism for preventing CSRF (Cross-Site Request Forgery) attacks.

Three values of SameSite

  1. Strict (strict mode)

    • Completely prohibits cross-site requests from carrying Cookies
    • Most secure but poor user experience
    • Example: Set-Cookie: token=xyz; SameSite=Strict
    • Use cases: banking, payment, and other high-security websites
  2. Lax (relaxed mode)

    • Allows some safe cross-site requests to carry Cookies
    • Balances security and user experience
    • Example: Set-Cookie: token=xyz; SameSite=Lax
    • Allowed requests: GET requests, top-level navigation, form GET submissions
    • Disallowed requests: POST requests, iframes, images, scripts, etc.
  3. None (allow cross-site)

    • Allows all cross-site requests to carry Cookies
    • Must be used with the Secure attribute
    • Example: Set-Cookie: token=xyz; SameSite=None; Secure
    • Use cases: third-party login, cross-domain API calls

CSRF protection principle

  • Attackers cannot carry target website Cookies in requests initiated from malicious websites
  • Even if the user is logged into the target website, cross-site requests cannot pass authentication

Browser compatibility

  • Chrome 51+, Firefox 60+, Safari 12+, Edge 79+
  • Old browser versions default behavior is equivalent to None

Best practices

  • General websites use SameSite=Lax
  • High security requirements use SameSite=Strict
  • Use SameSite=None; Secure when cross-domain is needed
  • Combine with CSRF Token for dual protection
标签:Cookie