I have a website where a user can input stuff in input feilds and submit it. When submitted, that data is then send to my server via a POST request and saved to my database.
However, those user submitted inputs are also send back to my front-end for all user to see, and it is loaded in using innerHTML. My Question is if I need to sanitize / purify those input feilds on my server to prevent XSS attacks. I assume it doesnt help doing it on the front-end? If so, it would be nice if you can help point me in the right direction for how this can be acheived?
Front-end:
// submit data
my_form.addEventListener("submit", async (e) => {
e.preventDefault();
await fetch('/post-data', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ input: my_input.value })
}).then(res => res.json())
});
// get data
async function load_data() {
const data_array = await fetch('/get-data');
data_array.forEach((data) => {
my_div.innerHTML = `<p>${data}</p>`;
});
}
load_data();
Back-end:
// * UserData is my mongoose schema as I am using mongoDB for my database, but thats besides the point.
router.post("/post-data", async (req, res) => {
await UserData.create({ data: req.body.input });
return res.json({ success: true });
});
router.get("/get-data", async (req, res) => {
const my_data = await UserData.find();
return res.json({ data: my_data });
});
CodePudding user response:
Are you using a frontend framework such as React or Angular? In such case both these framework have built-in sanitization according to their docs. Please see React XSS Guide: Examples and Prevention and Angular Security
Now If you are not using a framework you need to sanitize the input in backend or frontend.
My recommendation: Always validate input in server side when possible.
CodePudding user response:
Yes, as a rule of thumb, you want to expose as little information to the client as you can get away with (similar to the principle of least privilege). Don't expose data from your database to your client that is not explicitly needed. You want to minimize the chances that a malicious person gets ahold of data that could be use to compromise the security of your application.