How to prevent XSS attacks using SpringMVC + Jackson application?

The script for scrolling sites contains many rules to protect against XSS attacks. I would like to implement these suggestions in my web application that uses Spring MVC + Jackson + JPA + Hibernate Bean Validation. As an example, consider the following code, similar to what I have in my application.

public class MessageJson { @NotEmpty // Bean Validation annotation private String title; @NotEmpty private String body; // ... etc getters / setters } public class BolgPostController { @RequestMapping(value="messages",method=RequestMethod.POST) public void createMessage(@Valid @RequestBody MessageJson message) { // **Question** How do I check that the message title and body don't contain // nasty javascripts and other junk that should not be there? // Call services to write data to the datababse } @RequestMapping(value="messages",method=RequestMethod.get) public @ResponseBody List<MessageJson> createMessage() { // get data from the database // **Question** How do I escape all the data in the list of MessageJson before I send it back to the data. } } 

I can see the following ways to implement winding rules:

  • Option A Implement them manually in each controller method.
  • Option B: Configure some extension on Spring MVC that can do this for me automatically
  • Option C: Configure Jackson so that it can do this for me as most of my I / O goes through Jackson

I am looking for some SpringMVC configuration examples in any of these three options, with preference for options B and C.

+4
source share
1 answer

This would be easiest to do in property setters (e.g. setTitle() for title property) when reading JSON.

Or, if you are thinking of escaping extra characters (for example, to prevent embedding HTML markup), check out this blog post: Escaping HTML characters in JSON with Jackson .

+4
source

Source: https://habr.com/ru/post/1435581/


All Articles