I am currently developing a REST API with Java EE and MySQL, it will feed Data to a Android App. The Data comes from an AngularJS Frontend. So my questions are, when: When do I escape the data? Before it is filled in the prepared statements? When I deliver the JSON? Both?

And how: How should I escape the data? I currently am fiddling around with ESAPI and encodeForHTML - the problem here is, that is escapes stuff like @ and :) which I would like to support.


When do I escape the data?

Basically, as late as possible. The database is somewhere to store data, it is not a place to encode (escape) data. Of course use parameterised prepared statements to prevent any SQL injection attacks, but that should be as far as you take it. Your goal for writing to the database is simply to store the data successfully and to avoid any attacker breaking context and manipulating any queries to their own advantage.

Always think if a client/manager/supplier needs an export of the data, it is much easier if this data is already in plain format. It can become a headache if you then have to start converting it from HTML/JSON and then back into the correct format for export.

So the solution is to encode for JSON (but not HTML) when you deliver the JSON (preferably using a tried and tested Java JSON encoder).

You don't mention how you are rendering in your Android app. If you are using a non web control then you don't need to escape at all. If the controller doesn't interpret HTML and you are simply setting text elements then the application will not run any injected scripts. If you are generating a webview in Android on the client then you should HTML encode at this point.

  • Thank you, it makes things a lot clearer! :) The App will use non-web controls, so it should be fine on that side. – JoJae May 24 '15 at 10:05

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.