security
Cookie Security
Cookies are sent automatically with matching HTTP requests, so their scope and security flags matter. Authentication cookies deserve stricter handling than ordinary preferences.
Core Controls
- Use
Secureso sensitive cookies travel only over HTTPS. - Use
HttpOnlyfor session cookies so JavaScript cannot read them. - Choose a deliberate
SameSitepolicy and understand cross-site login flows. - Keep domain and path scope as narrow as practical.
- Do not store sensitive plaintext data in client-controlled cookies.
Set Strong Defaults For Authentication Cookies
<?php
declare(strict_types=1);
setcookie('__Host-session', 'opaque-session-id', [
'expires' => 0,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
echo 'Authentication cookie prepared.' . PHP_EOL;
// Prints:
// Authentication cookie prepared.
The __Host- prefix requires Secure, path=/, and no Domain attribute in supporting browsers. That is a useful default for a host-only session cookie.
Choose Attributes For The Cookie's Job
HttpOnly is appropriate when JavaScript does not need the value. Secure keeps sensitive cookies on HTTPS. SameSite=Lax works for many first-party browser applications. Cross-site embedded flows may need SameSite=None; Secure, but that should be an explicit design decision.
Keep Domain unset unless subdomain sharing is required. A broad domain increases where the browser sends the cookie.
Cookies Are Still Client Input
A preference cookie can use an allow-list and a fallback. An authentication cookie should normally contain only an opaque identifier that maps to server-side state.
Signed or encrypted cookies can protect integrity or confidentiality, but they still need expiry, rotation, and careful scope. Do not store a plain role or user ID and treat it as authoritative.
In Application Work
Signed or encrypted cookies still need expiry and scope rules. A browser cookie is client-controlled input even when the application created it earlier.
What To Check
Before moving on, make sure you can choose cookie attributes for the cookie's job, explain the __Host- prefix, keep scope narrow, and treat cookie values as client-controlled input.
Practice
Practice: Choose Session Cookie Options
Requirements
- Set secure, HTTP-only, same-site, and path options.
- Explain why a preference cookie may differ from a session cookie.
- Treat cookie values as untrusted input.
- Describe the HTTPS requirement.
Show solution
Review Points
- Use
Secureso sensitive cookies travel only over HTTPS. - Use
HttpOnlyfor session cookies so JavaScript cannot read them. - Choose a deliberate
SameSitepolicy and understand cross-site login flows. - Keep domain and path scope as narrow as practical.
- Do not store sensitive plaintext data in client-controlled cookies.