Practice: CORS
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most CORS work is three quick judgements: are these two URLs the same origin, will the browser send a preflight, and which header is wrong in the answer. This optional page checks all three before you move on.
Same origin or cross-origin: three checks
The program below prints SAME or CROSS for seven page and API URL pairs, using the three checks.
Example 1 · Classify URL pairs
import java.net.URI;
public class OriginPairs { static String url(String scheme, String hostAndPort, String path) { return scheme + "://" + hostAndPort + path; }
static String origin(String url) { URI uri = URI.create(url); String scheme = uri.getScheme().toLowerCase(); int defaultPort = scheme.equals("https") ? 443 : 80; int port = uri.getPort() == -1 ? defaultPort : uri.getPort(); return scheme + "://" + uri.getHost().toLowerCase() + ":" + port; }
static void classify(String page, String target) { boolean same = origin(page).equals(origin(target)); System.out.println((same ? "SAME " : "CROSS ") + page + " -> " + target); }
public static void main(String[] args) { classify(url("http", "localhost:3000", "/cart"), url("http", "localhost:3000", "/api/v1/products")); classify(url("http", "localhost:3000", "/cart"), url("http", "localhost:8080", "/api/v1/products")); classify(url("https", "shoplite.example", "/"), url("https", "SHOPLITE.example", "/api/v1/products")); classify(url("http", "shoplite.example", "/"), url("http", "shoplite.example:80", "/api/v1/products")); classify(url("https", "shoplite.example", "/"), url("https", "www.shoplite.example", "/api/v1/products")); classify(url("https", "shoplite.example", "/"), url("http", "shoplite.example", "/api/v1/products")); classify(url("http", "localhost:3000", "/"), url("http", "[::1]:3000", "/api/v1/products")); }}SAME http://localhost:3000/cart -> http://localhost:3000/api/v1/products CROSS http://localhost:3000/cart -> http://localhost:8080/api/v1/products SAME https://shoplite.example/ -> https://SHOPLITE.example/api/v1/products SAME http://shoplite.example/ -> http://shoplite.example:80/api/v1/products CROSS https://shoplite.example/ -> https://www.shoplite.example/api/v1/products CROSS https://shoplite.example/ -> http://shoplite.example/api/v1/products CROSS http://localhost:3000/ -> http://[::1]:3000/api/v1/products
What this code does
url()joins scheme, host and port;origin()fills in the default port and lower-cases scheme and host, soSHOPLITE.exampleand:80do not create false differences (lines 3 and 4).- The last three lines are the classic traps:
www.is another host,httpandhttpsdiffer, and[::1](IPv6 localhost) is notlocalhost.
Two URLs have the same origin when the scheme, the host and the port are all equal, after filling in the default port (80 for http, 443 for https) and lower-casing the host. Compare them in that order and stop at the first difference; paths, query strings and fragments never matter.
The traps are always the same few: a sub-domain such as www. or api. is a different host, localhost, 127.0.0.1 and [::1] are three different hosts, and http versus https changes both the scheme and the default port.
Predicting the preflight and the answer it needs
The program below prints the preflight the browser sends and the minimum answer the API must give, for four calls.
Example 2 · Predict the preflight and the answer
import java.util.Locale;import java.util.Map;import java.util.Set;import java.util.TreeSet;
public class PreflightPlan { static final Set<String> SAFE = Set.of("accept", "accept-language", "content-language"); static final Set<String> FORM_TYPES = Set.of("application/x-www-form-urlencoded", "multipart/form-data", "text/plain");
// Prints the preflight the browser sends and the minimum answer the API must give (simplified rule) static void plan(String origin, String method, Map<String, String> headers) { TreeSet<String> unsafe = new TreeSet<>(); headers.forEach((name, value) -> { String lower = name.toLowerCase(Locale.ROOT); boolean formType = lower.equals("content-type") && FORM_TYPES.contains(value.split(";")[0].trim().toLowerCase(Locale.ROOT)); if (!SAFE.contains(lower) && !formType) { unsafe.add(lower); } }); boolean simpleMethod = Set.of("GET", "HEAD", "POST").contains(method); System.out.println(method + " " + headers.keySet()); if (simpleMethod && unsafe.isEmpty()) { System.out.println(" no preflight; the response needs Access-Control-Allow-Origin: " + origin); return; } String list = String.join(",", unsafe); System.out.println(" preflight asks: method " + method + (list.isEmpty() ? "" : ", headers " + list)); System.out.println(" answer needs : Allow-Origin " + origin + ", Allow-Methods with " + method + (list.isEmpty() ? "" : ", Allow-Headers with " + list)); }
public static void main(String[] args) { String page = "https://shoplite.example"; plan(page, "GET", Map.of()); plan(page, "POST", Map.of("Content-Type", "application/json")); plan(page, "PUT", Map.of("Authorization", "Bearer eyJ...")); plan(page, "POST", Map.of("Content-Type", "multipart/form-data; boundary=x")); }}GET [] no preflight; the response needs Access-Control-Allow-Origin: https://shoplite.example POST [Content-Type] preflight asks: method POST, headers content-type answer needs : Allow-Origin https://shoplite.example, Allow-Methods with POST, Allow-Headers with content-type PUT [Authorization] preflight asks: method PUT, headers authorization answer needs : Allow-Origin https://shoplite.example, Allow-Methods with PUT, Allow-Headers with authorization POST [Content-Type] no preflight; the response needs Access-Control-Allow-Origin: https://shoplite.example
What this code does
- The JSON login asks for
content-type; thePUTwith a token asks forauthorization. Each line says what the server's preflight answer must contain. - The last call is a
multipart/form-dataupload: the; boundary=xpart does not count, the media type is form-like, so no preflight is needed.
A cross-origin call is preflighted unless it is GET, HEAD or POST with only safe headers and a form-like Content-Type (or none). For a preflighted call, write down the Access-Control-Request-Method and the sorted, lower-case Access-Control-Request-Headers; the server's answer must allow exactly those.
For ShopLite this gives a short rule. Public GET reads are simple. Login (JSON body) asks for content-type. Every signed-in call asks for authorization, and a signed-in write with JSON asks for authorization,content-type. The answer always needs the exact page origin in Access-Control-Allow-Origin.
Predict the output
What does the preflight ask?
Pick the Access-Control-Request-Headers value the browser sends.
Round 1 of 2
A signed-in customer saves a profile change.
Range header, very long header values) are left out.From an error message to the fix
The table below pairs real Chrome messages with the first thing to fix.
Example 3 · Real Chrome messages and their first fix
Message in the console (after "blocked by CORS policy:") First thing to fix-------------------------------------------------------------------- ------------------------------------------No 'Access-Control-Allow-Origin' header is present on the requested CORS is not set up for this path/origin,resource. or something answered before the CorsFilterResponse to preflight request doesn't pass access control check: ... the OPTIONS answer: usually 401 from security, fix with http.cors(...) in the chainRequest header field x-trace-id is not allowed by allow that header, or stop sending itAccess-Control-Allow-Headers in preflight response.The 'Access-Control-Allow-Origin' header has a value '...' that is allowed origin typo: scheme, host, port,not equal to the supplied origin. trailing slash, localhost vs 127.0.0.1The value of the 'Access-Control-Allow-Origin' header in the response '*' with credentials: list exact originsmust not be the wildcard '*' when the request's credentials mode is (or drop credentials if you use tokens)'include'.The value of the 'Access-Control-Allow-Credentials' header in the the page sends credentials: 'include' butresponse is '' which must be 'true' when the request's credentials the server does not allow credentialsmode is 'include'.Every message above was produced by Chrome in this module's test runs. Step 1: find the URL and origin in the first half of the message. Step 2: if an OPTIONS request failed in the Network tab, it is a preflight problem. Step 3: repeat the request with curl -i (and -X OPTIONS for a preflight) and compare the headers.
What this code does
- The first two messages mean no CORS headers came back at all; the rest mean CORS headers came back but one of them did not fit the request.
- A message containing
preflightpoints at theOPTIONSanswer. In a Spring Security app the usual cause is that CORS is not in the security chain, so the preflight got401.
Chrome's CORS messages have one shape: Access to fetch at '<URL>' from origin '<page origin>' has been blocked by CORS policy: and then a reason. The reason names the header or the step that failed, and it nearly always points to one setting.
Then prove the fix outside the browser. Repeat the call with curl -i and an Origin header, and for a preflight use curl -i -X OPTIONS with the two Access-Control-Request-* headers. Change one setting, restart, and run the same curl again until the headers match what the browser needs.
Interview drill: explaining CORS in one minute
A strong answer has four parts. First, the same-origin policy: browsers stop a page from reading responses from another origin, because they attach your cookies to every request. Second, CORS: the server relaxes that rule for named origins with Access-Control-Allow-* headers. Third, the preflight: for non-simple requests the browser asks with OPTIONS first. Fourth, the limit: CORS protects users in browsers, not the server, so curl ignores it and authentication still decides who may do what.
Then add one Spring sentence: rules in a CorsConfigurationSource bean, switched on with http.cors(...) so the CorsFilter answers preflights before authentication, with exact origins per profile and no * with credentials.
Finish up
Mark complete & continue
Next: Mini project: a browser client for ShopLite