Home > Enterprise >  How to use DOMPurify just on one specific user input filed?
How to use DOMPurify just on one specific user input filed?

Time:11-04

I need to demonstrate the XSS attack and how to prevent it. I made a simple web app that asks the user his first name and surname and prints "Welcome" together with his name and surname. Before using DOMPurify to prevent an XSS attack I was able to write a script in the input field and an XSS attack was successful. Finally, what I want to do is be able to perform an attack from the name input field and prevent an attack from the surname input field. This is my code:

function cleanData(userInput){
    return DOMPurify.sanitize(userInput);
}

function myFunction() {
    let name = document.querySelector("#name");
    let surname = document.querySelector("#surname");
    let message = document.querySelector("#message");

    const profileData = userInput(
        $(surname)
    );

    message.innerHTML = "Welcome "   name.value   surname.value;
} 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.4.0/purify.min.js"></script>
    <h1>Hi! What's your name?</h1>
    <input type="text" id="name" placeholder="name ...not sanitized " />
    <input
      type="text"
      id="surname"
      placeholder="surname ...sanitized "
    />
    <br />
    <br />
    <button onclick="myFunction()">Submit</button>
    <h1 id="message"></h1>

I would say that I am failing to use DOMPurify just on surname input field and don't know how to fix that.

CodePudding user response:

Pass surname to cleanData

function cleanData(userInput){
    return DOMPurify.sanitize(userInput);
}

function myFunction() {
    let name = document.querySelector("#name");
    let surname = document.querySelector("#surname");

    message.innerHTML = "Welcome "   name.value   cleanData(surname.value);
} 
  • Related