8

I am trying to set up session cookies in my Node server, which is the backend for an Electron app. I am trying to follow this guide.

https://firebase.google.com/docs/auth/admin/manage-cookies

The first thing I am confused about is where this function comes from in the "Sign In" section: const csrfToken = getCookie('csrfToken') Is 'getCookie' a function I am supposed to write myself?

I am also not fully following the logic of the "create session cookie" snippet:

const csrfToken = req.body.csrfToken.toString();
  // Guard against CSRF attacks.
  if (csrfToken !== req.cookies.csrfToken) {
    res.status(401).send('UNAUTHORIZED REQUEST!');
    return;
  }

So this looks like it's checking to see if the request body's CSRF token is the same thing set in the request cookie's CSRF token? Is this because someone might set the CSRF token manually (i.e. using Postman) but such a request won't go through because it's not in req.cookies? Does this imply that one is not supposed to be setting req.cookies in their client-side code?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
sleigh_bells
  • 126
  • 2
  • 7

1 Answers1

6

getCookie is a basically a cookie getter. You can write it yourself or lookup the implementation online. As for the CSRF check, this is a basic defense against CSRF attacks. The CSRF token is set in a cookie and then returned back in the post body. The backend will confirm that the CSRF token in the cookie matches the token in the POST body. Basically the idea here is that only requests coming from your website can read the cookie and pass it in the request in the POST body. If the request is coming from another website, they will not be able to read the cookie and pass it in the POST body. While the CSRF token cookie will be always be passed along the request even when coming from other origins, the token will not be available in the POST body.

A quickstart node.js implementation is available at: https://github.com/firebase/quickstart-nodejs/tree/master/auth-sessions

bojeil
  • 29,642
  • 4
  • 69
  • 76
  • I would like to ask a doubt, please: If the server relies only on comparing the CSRF token inside the cookie with the value inside the POST body to see if they match, it seems to me that it would be possible to by-pass this protection, because the attacker could set the cookie value when fabricating a request - so, they could set a fake CSRF token in the cookie along with the request, with a matching fake POST body token. The server would then compare both values and find them equal. Am I missing something? – favq Nov 06 '18 at 11:04
  • That would not come from the user's browser (you can't set a cookie for a different domain). It would come from the attacker's device. Hence there is no value to this attack. – bojeil Nov 07 '18 at 19:04