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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad