Why CSRF is not working in only POST route While working in the rest of other Post routes?

你说的曾经没有我的故事 提交于 2021-01-07 03:32:31

问题


I am getting the CSRF forbidden error. However CSRF is working fine in the rest of the application like post route of logout, signUp, Signin deleteing anything et c..

But when I perform the post action in only one route `/addProduct" I am getting the error Note that I am generating my CSRF token before routes declaration.

I am attaching the main file code and the front end code of addProduct.

Here is my main file code where I am generating token and including it in all routes

app.use(csrfProtection);
app.use(flash());


// USed to include token and isLoggedIn information to render in every page
app.use((req, res, next) => {
  res.locals.isLoggedIn = req.session.isLoggedIn;
  res.locals.csrfToken = req.csrfToken();
  res.locals.user= req.session.user;
  next();
});



// app.use((req, res, next) => {
//   // throw new Error('Sync Dummy');
//   if (!req.session.user) {
//     return next();
//   }});

app.use(multer({ storage: fileStorage,fileFilter:fileFilter }).single('image'));

app.use(shopRoute);
app.use(authRoute);
app.use('/admin',adminRoute);
app.use(errorController.get404);

This is the front end code for ADD_Product.ejs. Here I am including hidden input as well... to get CSRF value back to check it...

<form action="<%=path%>" enctype="multipart/form-data" method="POST">

    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" class="form-control" id="title" name="title" value="<%=product.title%>" >

      </div>
      <div class="form-group">
        <label for="price">Price</label>
        <input type="text" class="form-control" id="price" name="price" value="<%=product.price%>">
      </div>
      <div class="form-group">

        <input type="file" class="form-control-file" id="exampleFormControlFile1" name="image" value="<%=product.imageUrl%>">
      </div>
      <div class="form-group">
        <label for="exampleFormControlTextarea1">Description</label>
        <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="description" value="<%=product.description%>"></textarea>
      </div>


      <% if (path=="/admin/edit") { %>
        <input type="hidden" name="productId" value="<%=product._id%>">
      <% }  %>

      <input type="hidden" name="_csrf" value="<%= csrfToken %>"> 
      <button type="submit" class="btn btn-primary btn-lg center">+ </button>
</form>

来源:https://stackoverflow.com/questions/61638855/why-csrf-is-not-working-in-only-post-route-while-working-in-the-rest-of-other-po

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!