2

In my web app, I want to send a cross-domain AJAX request to another site. I want to take the text that the user enters in a form and append that text to the query string in the URL I send the request to, so I escape the user's text using encodeURIComponent() first, like so:

function sendAJAXRequext(textThatUserEntered) {
  const hopefullyThisStringIsSafe = encodeURIComponent(textThatUserEntered);
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `https://www.example.com/api?query=${hopefullyThisStringIsSafe}`);
  // snip...
  xhr.send();
}

Is using encodeURIComponent() good enough to ensure there aren't any ways to inject something evil into the URL I request, or is there something additional I need to do to sanitize textThatUserEntered?

1
  • Note that there is a limit on the length of urls (usually imposed by the server), so it may not work if the user enters a long text in your form.
    – Ángel
    Jan 6, 2017 at 22:18

2 Answers 2

4

Yes, encodeURIComponent() is the correct way to safely fill a query parameter with untrusted data.

E.g., to set a parameter q to a user-supplied userString, this is fine and safe:

`https://www.example.com/api?q=${encodeURIComponent(userString)}`

Safe here means that the user string represents a single URI component and an attacker will have no way of introducing a new parameter or change the URL to a different target, because delimiters like &, ?, #, / are URL-encoded. But it does not mean the value is somehow safe for further processing on the target site. It may still cause, say, an injection vulnerability on the target server.

Also note that some characters not commonly considered delimiters are excluded (notably !, ', (, ), *) for which Mozilla proposes this wrapper function:

function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}
-1

As additional recommendation, JavaScript is interpreted on client side, then it can be manipulated for an expert user and bypass the encoding methods, also if someone knows how send a request to your application, then he can build a request with unsanitized parameters, then you have to implement the same validations or encoding methods on server side. JavaScript and AJAX ara good to improve the performance of an application, but the security which they offer aren't enough, the security mesaures always must be on server side.

I hope this information helps you.

1
  • Thanks, but I already understand this. This question isn't about trying to use client-side code as my only line of defense, but rather about one specific piece of code. My goal, of course, is to make my app's full stack as secure as possible.
    – Kevin
    Jan 7, 2017 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.