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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With