How to add assign csrf token in the HTML submit form
19,328
You can add hidden field for _csrt
token. Here is example code
<html>
<body>
<form ref='uploadForm'
id='uploadForm'
action='http://localhost:8000/upload'
method='post'
encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type="hidden" name="_csrf" value="<your_csrf_token>" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
Author by
Anson Aştepta
Updated on June 17, 2022Comments
-
Anson Aştepta almost 2 years
My site is under csurf protection at the moment.
I have assigned all my ajax call with csrf token like below
"/data/someAPI?_csrf="+ $("#_csrf").val
and it works just fine with all function I had.But now I am writing a file upload function and most of the tutorials on the internet are using sumbit form to do so.
So I wrote something like
Node.js
app.post('/upload', function(req, res) { if (!req.files) return res.status(400).send('No files were uploaded.'); // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file let sampleFile = req.files.sampleFile; // Use the mv() method to place the file somewhere on your server sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) { if (err) return res.status(500).send(err); res.send('File uploaded!'); }); });
Solved
HTML
<html> <body> <form ref='uploadForm' id='uploadForm' action='http://localhost:8000/upload?_csrf=<your_csrf_token>"' method='post' encType="multipart/form-data"> <input type="file" name="sampleFile" /> <input type='submit' value='Upload!' /> </form> </body> </html>
I directly assigned the token in the form action and it works fine.
-
aquaman over 6 yearsWhy not do it as you are doing in
ajax
call? i.e. define token in formaction
. -
Anson Aştepta over 6 years@aquaman do you mean i should <input type='hidden' name='form-control' value='{{_csrf}}'> put this line within the form?
-
aquaman over 6 yearsI meant modify your form as
action="/upload?_csrf=<your_csrf_token>"
. And well what you suggested in another option you can try. -
Anson Aştepta over 6 yearsthanks i solved it!!! @aquaman
-
Joshua M. Moore over 5 yearsQuick question, how do you obtain that CSRF token in the first place?
-
-
Rudra21 over 6 years@BhavaniSolanki : After implementing CSRF solution hidden field comparing server side , the problem is , when open new tab with same URL then hidden filed comes null.Server side condition is if CSRF hidden field null then its attack.is it expected behavior ?