What browsers add: same-origin, CORS and cookies
A browser sends the same HTTPThe Hypertext Transfer Protocol, the rules browsers, apps, and servers use to send requests and responses on the web. as curl, but it must keep many sites and sign-ins safely apart. Its origin, sharing and cookie rules decide what each page can do, and developer tools let you watch those decisions happen.
Origins
Every request you have sent in this course went from your terminal to a server and back. A browser sends the same HTTP, but it has a harder job. It shows pages from many sites at once, each page can run JavaScript (small programs that arrive with the page), and the browser holds your sign-ins to all of those sites. A page from a site you visited once should not be able to use your bank's sign-in. Browsers add rules to keep sites apart, and the unit those rules use is the origin.
An origin is three parts of a URL taken together: the
scheme, the host and the
port. For https://app.example.com/notes,
the origin is https://app.example.com, with the default
HTTPSHTTP protected by TLS, so traffic is encrypted and checked for changes while it travels. It protects the connection, but does not prove that the site at the other end is honest. port 443. The path does not count. Two URLs have the same origin
only when all three parts match:
Compared with https://app.example.com/notes | Same origin? | Why |
|---|---|---|
https://app.example.com/settings?tab=2 | Yes | Only the path and query differ |
https://app.example.com:443/notes | Yes | 443 is the default port for HTTPS, so it is the same port |
http://app.example.com/notes | No | Different scheme |
https://app.example.com:8443/notes | No | Different port |
https://api.example.com/notes | No | Different host |
https://example.com/notes | No | Different host, even though it is the parent domain |
The same-origin policy
The same-origin policy is the browser rule that keeps origins apart. A page's scripts can read what comes from its own origin. They cannot read responses from another origin unless that origin allows it.
Picture a page on https://games.example whose script asks
the browser to fetch https://mail.example.com/inbox, with
your cookies for that site attached. The mail server sees you, signed
in, and answers with your inbox. Without the same-origin policy, the
game's script could read that answer and send it anywhere. With it,
the browser keeps the response from the script.
Notice what the policy blocks: reading responses, not
sending requests. Pages have always been able to link
to other sites, submit forms to them, and load their images and
scripts, and all of those send requests across origins. A script can
send many cross-origin requests too. The browser adds an
Origin header to them, naming the page's origin, and page
scripts cannot change it. What the script gets back is the part the
policy controls.
Because sending is allowed, a server cannot assume that every request
carrying your cookies was one you meant to make. When another site
makes your browser send a request you did not intend, that is called
cross-site request forgeryAn attack in which another site makes your browser send a request you did not intend, and the receiving application treats it as yours because your session cookie came with it. Cookie settings such as SameSite reduce it by keeping the cookie off requests other sites start.. The SameSite cookie attribute, later in this
lesson, is one defense against it.
Sharing across origins with CORS
Many applications need to cross origins on purpose. A page on
https://app.example.com may load its data from an APIAn application programming interface: a defined way for software to interact with a service. A web API offers endpoints where other programs send HTTP requests. on
https://api.example.com. CORS,
Cross-Origin Resource Sharing, lets a server tell browsers which other
origins may read its responses. It does this with response headers
whose names start with Access-Control-. The main one names
the origin that may read the response:
Access-Control-Allow-Origin: https://app.example.com
The value can also be *, which lets any origin read the
response. That suits public data, such as an open dataset, and never
data that depends on who is asking. When the answer depends on the
requesting origin, the server also sends Vary: Origin, so
caches keep a separate copy for each origin.
For simple requests, the browser just sends the request with its
Origin header and then checks the response. A simple
request is a GET, HEAD or POST
with only a few standard headers, such as Accept, and with a Content-Type that an
ordinary HTML form could also send, such as
application/x-www-form-urlencoded or
text/plain. If the response does not allow the page's
origin, the page gets an error instead of the response. The server
still received and handled the request.
Anything else gets a preflight first. That includes
methods such as PUT and DELETE, a JSONA text format for structured information, written as named values inside curly braces. APIs, tokens, and discovery documents all use it. body
with Content-Type: application/json, and headers such as
Authorization. Forms could never send those, so servers
written before CORS never expected them from another site. The browser
asks first, with an OPTIONS request that describes the
real one. Suppose the page on https://app.example.com runs
this JavaScript to update a note:
fetch('https://api.example.com/notes/7', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Buy milk' }),
});fetch asks the browser to send a request from the page: here a PUT with a JSON body, which JSON.stringify writes out from the object between the braces. Because the method is PUT and the body is JSON, the browser first sends this preflight:
OPTIONS /notes/7 HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-typeIf the API allows it, the answer says so:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, PUT, DELETE
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 600
Vary: Origin
The origin, the method and the header are all allowed, so the browser
sends the real PUT. The API's response to it must carry
Access-Control-Allow-Origin again before the page can read
it. Access-Control-Max-Age: 600 lets the browser remember
this answer for up to 600 seconds and skip the preflight for similar
requests. If the preflight answer had not allowed the origin, the
browser would never have sent the PUT at all: the note on
the API stays as it was, and the page gets an error. That is the
difference from a simple request, which reaches the server and is
checked only on the way back.
A preflight never carries cookies or an Authorization
header; it only asks. The real request carries cookies across origins
only when the page asks for that, with
credentials: 'include' in fetch, and then
the rules tighten. The preflight's answer and the real response must
both carry Access-Control-Allow-Credentials: true, and
both must name the origin exactly, because * is not
accepted for requests with credentials. For the same reason, a
* in Access-Control-Allow-Methods or
Access-Control-Allow-Headers stops being a wildcard and
is read as a literal name. One more rule holds even without
credentials: Access-Control-Allow-Headers: * never covers
Authorization, which the server must always name.
CORS loosens the same-origin policy. It does not protect the server. The browser enforces it for the page's sake, and any program that is not a browser can call the API whatever its CORS headers say. The API still has to authenticate and authorize every request on its own.
Headers that tighten the browser
A few more response headers ask the browser to be stricter than its defaults, and two of them matter on every sign-in page.
Strict-Transport-Security, usually called
HSTS, tells the browser to use only HTTPS for this
host from now on:
Strict-Transport-Security: max-age=31536000; includeSubDomains
For the next max-age seconds, a year here, the browser
turns any http:// address for the host, and with
includeSubDomains for its subdomains, into
https:// before it sends anything, and it no longer lets
the person click past a certificateA signed statement that a public key belongs to a name, such as a website's hostname, for stated purposes and a limited period. A certificate authority signs it, so software that trusts the authority can connect the key to the name. error. Without it, someone who
types photos.example.com starts with a plain HTTP request
that anyone on the path could answer with a fake sign-in page. The
browser learns the header from its first HTTPS visit, so sites that
want protection even on the very first visit also ask to be added to
the preload list built into browsers.
When you follow a link or a page loads an image or script, the
browser usually tells the destination where you came from, in a
request header spelled Referer (a misspelling that the
standard kept). If the page's URL holds a one-time code or a tokenA piece of data issued by a trusted service that a client presents as a credential, for example to call an API or to report a sign-in. Some tokens carry readable claims; others are random strings that only the issuer can interpret.,
that header can hand it to whoever runs the image server or the
linked site. Referrer-Policy limits what is sent.
no-referrer sends nothing, and
strict-origin-when-cross-origin, the default in current
browsers, sends only the origin to other sites and nothing at all
from an HTTPS page to an HTTP one:
Referrer-Policy: no-referrer
A third header, Content-Security-Policy, decides which
scripts a page may run.
Cross-site scripting and where tokens live
explains it with the problem it solves.
Watching the browser with developer tools
Desktop browsers come with developer tools, a panel that shows what the browser does for the page in front of you. Press F12, or Ctrl+Shift+I on Windows and Linux and Cmd+Option+I on a Mac. Safari first needs "Show features for web developers" turned on in its Advanced settings. The panel opens next to the page, with a row of tabs.
The Network tab lists the requests the page makes
while the panel is open, so reload the page after opening it. Select a
request to see its method, its status codeThe three-digit number at the start of an HTTP response that says how the request went, such as 200 for success, 302 for a redirect, or 401 when authentication is needed., and the headers in both
directions: the Origin the browser added, the
Access-Control- headers that came back, and the
Set-Cookie and Cookie headers.
By default the list starts again each time the page navigates somewhere else. A sign-in usually passes through several pages in a row, each redirecting to the next, so the requests you most want to read vanish as you watch. Tick Preserve log at the top of the Network tab in Chrome, Edge and Safari, or turn on Persist Logs in the Network tab's settings menu in Firefox, and the list keeps every request across navigations.
The Network tab shows each request as it was sent, so it never shows
a URL's fragment, the part after #, because a browser
never sends that part to the server. To see the full address,
fragment included, look at the address bar, or type
location.href in the Console. To repeat a request from
your terminal, right-click it and choose Copy, then
Copy as cURL. On Windows, pick the bash or POSIX
version, because your terminal is Ubuntu. The copied command includes
the request's cookies and any
Authorization header, so treat it like a password.
The cookies the browser has stored are under
Application in Chrome and Edge, and under
Storage in Firefox and Safari. Each cookie is listed
with its value and its attributes, including whether it is
Secure and HttpOnly.
The Console tab shows the page's messages, including
the error a browser reports when the same-origin policy keeps a
response from a script. You can also type JavaScript there, and it
runs as part of the page. Typing document.cookie shows the
cookies the page's scripts can read, which never include an
HttpOnly one. Only run code you understand in the
Console: it can do anything the page can, with your sign-in. For the
same reason, treat what the panel shows, which includes real cookie
values, like a password when you share your screen.
Browser rules and curl
None of these rules exist in curl. The same-origin policy protects one
site's data from another site's scripts, and curl runs no scripts from
anyone. It reads every response it gets, ignores
Access-Control- headers, sends no Origin
header unless you add one, and forgets cookies as soon as it exits.
That makes it a good tool for seeing what a server tells browsers,
because you decide exactly what to send.
To see a server's CORS answer, send the Origin header a
browser would add, with -H, and show the response headers
with -i:
curl -sS -i -H "Origin: https://app.example.com" https://api.example.com/notes
To send a preflight by hand, set the method with -X OPTIONS
and add the two headers that describe the real request:
curl -sS -i -X OPTIONS \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: PUT" \
-H "Access-Control-Request-Headers: content-type" \
https://api.example.com/notes/7A backslash at the end of a line continues the command on the next line, which keeps long commands readable.
For cookies, curl uses a cookie jar, a text file that
plays the browser's part. -c FILE writes every cookie curl
knows about, including the ones the server just set, into the file when
curl finishes. -b FILE reads the file and sends the
cookies that match the request's host, path and scheme, following the same Domain, Path,
Secure and expiry rules as a browser. Use both to keep a
session going across several commands:
curl -sS -c jar.txt https://www.example.com/
curl -sS -b jar.txt -c jar.txt https://www.example.com/account
The jar has one cookie per line, with tab-separated fields: the host,
whether subdomains also receive it, the path, whether it is
Secure, the expiry time as a Unix timeA count of seconds since midnight UTC on 1 January 1970. JWT claims such as exp and iat use it, under the name NumericDate., which
Time and timestamps
explained, the name and the value. Example contents:
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
#HttpOnly_www.example.com FALSE / TRUE 1791360000 session 4f9c2a7d
The last line starts with # but is not a comment:
#HttpOnly_ in front of the host marks an
HttpOnly cookie, so a command that skips every line
starting with # would skip those cookies too. The real
comments start with # and a space. A jar can hold real session cookies, so
treat it like a password: keep it out of shared folders and delete it
when you are done. -b also accepts a cookie written
directly, such as -b "theme=dark", when you want to send
one without a file.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Ask for CORS answers and keep cookies in a jarSend Origin headers and CORS preflight requests the way a browser would, keep cookies across requests with a curl cookie jar, then watch your browser do the same in developer tools.