Beta

Create a tenant

A new tenant starts with its own users, OAuth settings, audit history and logs. You are its first Tenant Admin.

What browsers add: same-origin, CORS and cookies

A browser sends the same HTTP 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 HTTPS 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/notesSame origin?Why
https://app.example.com/settings?tab=2YesOnly the path and query differ
https://app.example.com:443/notesYes443 is the default port for HTTPS, so it is the same port
http://app.example.com/notesNoDifferent scheme
https://app.example.com:8443/notesNoDifferent port
https://api.example.com/notesNoDifferent host
https://example.com/notesNoDifferent 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 forgery. 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 API 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 JSON 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-type

If 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 browser asks with a preflight first. Only an answer that allows the origin lets the PUT go out; otherwise the browser never sends it.

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.

Cookies

HTTP does not remember anything between requests. Staying signed in showed how a session cookie keeps you signed in; this section looks at the rules the browser follows for it. A cookie is how a server gets the browser to remember something for it. The server sends a Set-Cookie header, the browser stores the cookie, and it sends the cookie back in a Cookie header on later requests to that server:

HTTP/1.1 200 OK
Set-Cookie: session=4f9c2a7d; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax

GET /inbox HTTP/1.1
Host: mail.example.com
Cookie: session=4f9c2a7d

The first part, session=4f9c2a7d, is the cookie's name and value. The rest are attributes, instructions to the browser about when to send the cookie. They travel only in Set-Cookie; the Cookie header carries just names and values.

AttributeWhat it controls
DomainWhich hosts receive the cookie. Without it, only the exact host that set it does (a host-only cookie). Domain=example.com also sends it to every subdomain, such as api.example.com.
PathWhich paths receive it. Path=/ means every path on the host.
Expires or Max-AgeWhen the browser deletes it: at a date, or after a number of seconds. Without either, it is a session cookie. Browser session restoration can retain it after a restart; the server still decides whether its value remains valid.
SecureSent only over HTTPS, never over plain HTTP.
HttpOnlyPage scripts cannot read it. The browser still sends it with requests.
SameSiteWhether it is sent on requests that another site caused: Strict, Lax or None.

SameSite uses a looser idea than an origin. A site is the scheme plus the registrable domain, the part of the name someone registers, such as example.com. So https://app.example.com and https://api.example.com are different origins but the same site. With Strict, the cookie goes only on requests that come from the same site. Lax also sends it when you follow a link from another site to this one, but not on other cross-site requests, such as a form POST from another site or a request made by another site's script, image or frame, a page shown inside another page. None allows the cookie on cross-site requests as well, and must be combined with Secure. Whether the browser really sends it there now depends on the browser's own rules too, as the next section explains. Many browsers treat a cookie without SameSite as Lax, but not all do, so servers set it explicitly.

A cookie's name can carry a promise as well. A name that starts with __Secure- is accepted only if it was set over HTTPS with the Secure attribute. A name that starts with __Host- must also have Path=/ and no Domain, so it belongs to exactly one host:

Set-Cookie: __Host-session=4f9c2a7d; Path=/; Secure; HttpOnly; SameSite=Lax

The browser refuses a __Host- cookie that breaks these rules, so a page on a neighboring subdomain, or a plain HTTP page, cannot set or replace it. That is why session cookies often use the prefix.

Notice that none of these rules mention ports: a cookie set by https://app.example.com:8443 is also sent to https://app.example.com. Each attribute closes a different gap. A session cookie works like a ticket, and whoever holds a copy can act as the signed-in person. Secure keeps it off unencrypted connections, where anyone on the path could copy it. HttpOnly keeps page scripts from reading it, although a hostile script in the page can still send requests that carry it. SameSite limits which cross-site requests carry it. None of them replaces the server's own check that the session is still valid and the request is allowed.

Third-party cookies

A cookie is third-party when the page in front of you belongs to one site and the request goes to another. A page can show another page inside itself, in a frame, and a frame can be hidden. A sign-in service's page loaded in a hidden frame inside the photo app is a typical case: the frame's requests go to the sign-in service, while the page you are looking at is the photo app. For years browsers sent SameSite=None cookies in these requests, and advertisers used them to follow people from site to site.

Browsers now add their own rules on top of SameSite. Safari blocks third-party cookies by default. Firefox gives every site you visit its own separate jar of third-party cookies, which it calls Total Cookie Protection, so a sign-in service framed inside the photo app sees a different jar from the one its own pages use. Chrome blocks them in private windows and for people who choose to, and it supports partitioned cookies, marked with the Partitioned attribute, which it likewise keeps in a separate jar for each top-level site. So a third-party cookie is often not sent at all, or comes from a jar that the service's own pages never see.

Several identity techniques were built on these cookies. A page could check in a hidden frame whether you were still signed in to the provider, renew its tokens silently in a hidden frame, or be told about a sign-out by the provider loading its logout page in a frame. When third-party cookies are blocked or partitioned, the frame arrives without the session cookie it needs: the check reports you as signed out, the silent renewal fails, and the logout page cannot find the session it should end. Session management and Front-channel logout look at what still works.

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 certificate 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 token, 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 code, 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/7

A 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 time, 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.

An API sends CORS headers that allow only https://app.example. Someone calls the API with curl from a terminal and sends no Origin header. What happens? 1 of 4

Choose one answer.

A photo app on https://photos.example renews its tokens by loading the sign-in service, https://login.example, in a hidden frame. In Safari the renewal always fails as if the person were signed out, although they are signed in at login.example. What is the most likely reason? 2 of 4

Choose one answer.

A page on https://app.example runs fetch to PUT a JSON note to https://api.example/notes/7. The API answers the preflight without any Access-Control-Allow-Origin header. What happens to the note? 3 of 4

Choose one answer.

A page on https://games.example hides a form that POSTs to https://mail.example/settings/forward. The mail site sets its session cookie with SameSite=Lax. When a signed-in person opens the game page, what does the browser do with the form? 4 of 4

Choose one answer.

Try it in the Lab

We value your privacy

We use cookies and similar technologies to enhance your browsing experience, and analytics to understand our traffic. By clicking "Allow all", you consent to optional analytics. Cookie Policy

Learn identity