Start learning free

LESSON 22 OF 58 · FULL-STACK: LOGIN WITH COOKIES

Someone Else's Page in JavaScript

Practice

A cookie belongs to a site, not to a page. When any page sends a request to localhost:3000, the browser can attach the cookies it keeps for localhost:3000, even when that page comes from http://evil.example. So a hostile page can hide a form that posts to /api/orders: if Ana's session cookie goes along, the server places an order she never asked for. This attack is called cross-site request forgery (CSRF).

Your cookie already has sameSite: "lax": the browser leaves it off a POST that another site starts. That holds only while nobody changes the setting; the check runs the same attack against a copy of your server with sameSite: "none", and the order goes through. So the server adds a second wall. A browser marks each POST with an Origin header, the site of the page that sent it, and the page can't change it.

A middleware passed to app.use runs before every route below it, and req.get reads a header. For example, this one logs where each request comes from:

app.use((req, res, next) => {
  console.log(req.method, req.path, req.get("Origin"));
  next();
});

A GET only reads, so it may come from anywhere, and a request with no Origin at all (a tool like curl, the check's own login) didn't come from someone else's page. Your server must answer:

POST /api/orders  (Origin: http://localhost:5173)  →  201  {"id": 8}
POST /api/orders  (Origin: http://evil.example)    →  403  {"error": "Requests from other sites are not allowed"}
hidden form from evil.example, sameSite: "lax"     →  403  (no cookie sent)
the same form, a copy with sameSite: "none"        →  403  (Ana's cookie sent, still refused)
Ana's orders                                       →  200  order 1 paid, order 3 paid

Your task: in server/app.js, write a middleware checkOrigin that answers 403 with {"error": "Requests from other sites are not allowed"} for a request that is not a GET and has an Origin other than http://localhost:5173, and have the app use it before the routes.


Assignment
Follow the Coding Tutorial to write checkOrigin below requireLogin and plug it into the app with app.use.


Hint
Three conditions joined with &&: not a GET, an Origin at all (req.get("Origin") is undefined when there is none), and not the storefront. Until app.use(checkOrigin) is written, the function never runs.


STEP 1 OF 6
    Ctrl + Enter to check

    Fsauth Csrf in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free