1 year ago
#76767

Ozure
403 invalid csrf token, Express, csurf, React and Axios
I am trying to implement CSRF protection to my API endpoints, I am using express and csurf, when making a post request using Axios from my react app I am receiving 403 invalid csrf token. I have been searching all over for a solution but could not find one that fits.
For example, I am trying to send an Axios request to log out from the app (delete the session cookie) and receive the error. A code that shows the error looks like that:
server.ts:
const router = express();
dotenv.config();
router.use(helmet...)
router.use(cookies());
router.use(express.static(path.resolve(__dirname, '../client/build')));
var production = process.env.NODE_ENV === 'production' ? true : false;
var csrfProtection = csurf({ cookie:{
httpOnly:production,
secure:production
} });
router.use(csrfProtection);
router.use(cors({ credentials: true, origin: true
,exposedHeaders:['itemsCount','notificationCount','courseCount'] }));
router.use((req, res, next) => {
res.cookie('XSRF-TOKEN', req.csrfToken(),{httpOnly:production,secure:production});
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, itemsCount');
if (req.method == 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
router.use('/api', userRoute);
const httpServer = http.createServer(router);
httpServer.listen(config.server.port, () =>
logging.info(NAMESPACE, `Server is running ${config.server.hostname}:${config.server.port}`));
user.ts:
router.post(`/${NAMESPACE}/logout`,verifyToken, logout);
userController.ts:
const logout = (req: Request, res: Response, next: NextFunction) => {
res.clearCookie('session');
return sendResponse(res, 200);
}
the axios request looks like that:
logout: () => axios.post(`/users/logout`, {},{withCredentials: true})
Both XSRF-TOKEN and _csrf cookies are secure and httpOnly.
I would much appreciate it if someone can point me to what I am doing wrong here.
Thanks.
node.js
reactjs
express
axios
csrf
0 Answers
Your Answer