Ad

Put Csrf Token On Every Route

i made a csrf implementation on my nodejs web app. but the csrf token only gets attached if i go through the /login route. how can i do that it gets implemented on every route without causing errors? or another idea for implementing it correctly?

i don't think that using a wildcard ** will help

this is the code for my csrf code:

app.use(
  attachCsrfToken(
    "/login",
    "csrfToken",
    (Math.random() * 100000000000000000).toString()
  )
);

function attachCsrfToken(url, cookie, value) {
  return function(req, res, next) {
    // console.log(req.url, url);

    if (req.url == url) {
      res.cookie(cookie, value);
    }

    next();
  };
}

Is there a better way of implementing it?

Ad

Answer

You can create a middleware which validates the user and url and add this to any route that you want to validate.

const express = require("express");
const router = express.Router();

function attachCsrfToken(req,res,next) {
    // validate request
    if (req.url == url) {
      res.cookie(cookie, value);
      next();
    }

    
    // if not valid throw error
    res.JSON({success:false,code:403,message:'Unauthorized Access'})
  };
router.use(
  "/api/someroute",
  attachCsrfToken,
  require("./handlers/somePath").someFunction
);

Ad
source: stackoverflow.com
Ad