SameSite Cookie and CSRF
SameSite Cookie Attribute
The SameSite attribute is a security feature for cookies that helps prevent Cross-Site Request Forgery (CSRF) attacks by controlling when cookies should be sent with requests. It tells the browser whether to include cookies in requests coming from different sites.
SameSite Attribute Values
The SameSite attribute has three possible values:
-
SameSite=Strict
- Cookies are only sent in first-party (same-site) requests.
- Cross-site requests do not include the cookie, even if the user has logged in.
- Best for security, but it may break functionality if users expect cookies to persist across tabs or external links.
- Example:
Set-Cookie: session_id=abc123; SameSite=Strict; Secure
- Example Scenario:
- A user logs into example.com.
- They click a link to another-site.com which redirects back to example.com.
- The session cookie is not sent, so the user may need to log in again.
2. SameSite=Lax (Default)
- Cookies are sent for same-site requests and GET cross-site requests that cause top-level navigation (like clicking a link).
- Cookies are NOT sent on cross-site POST, PUT, or AJAX requests.
- This prevents CSRF in most cases while keeping usability.
- Example:
Set-Cookie: session_id=abc123; SameSite=Lax; Secure
- Example Scenario
- A user logs into example.com.
- They click a link to example.com from another website.
- The session cookie is sent, so the user remains logged in.
- However, if an attacker tries to send a POST request via a malicious form, the cookie will not be sent, preventing CSRF.
-
SameSite=None (Allows Cross-Site Requests)
- Cookies are sent with all requests, including cross-site requests.
- Requires
Secureflag, meaning the cookie is only sent over HTTPS. - This is used when third-party services (e.g., authentication, embedded content) need to access the cookie.
- Example:
Set-Cookie: session_id=abc123; SameSite=None; Secure
Example Scenario:
- A third-party service (e.g., auth.example.com) needs to authenticate users across different sites.
- Cookies are included in cross-site requests, allowing authentication to work across domains.
When to Use Each SameSite Setting?
| SameSite Mode | Security Level | Use Case |
|---|---|---|
| Strict | High | Best for sites where security is the top priority and cross-site access is not needed (e.g., banking, admin panels). |
| Lax | Medium | Good balance between security and usability. Works well for most web apps. |
| None | Low (unless secured properly) | Needed when cross-site cookies are required (e.g., third-party authentication, payment gateways). Must be used with Secure. |
Conclusion
- Use
SameSite=Laxby default (as most browsers do) since it prevents CSRF in most cases. - Use
SameSite=Strictfor highly sensitive applications where you don’t want cookies to be leaked across sites. - Use
SameSite=None; Securewhen third-party cookies are needed, but ensure it’s over HTTPS.