4

Cross Site Scripting Cheat Sheet有许多防止 XSS 攻击的规则。我想在使用 Spring MVC + Jackson + JPA + Hibernate Bean Validation 的 Web 应用程序中实现这些建议。作为示例,请考虑以下与我的应用程序中的代码类似的代码。

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. 
     }
}

我可以看到以下实现备忘单规则的方法:

  • 选项 A在每个控制器方法中手动实现它们。
  • 选项 B为 Spring MVC 配置一些可以自动为我完成的扩展
  • 选项 C配置 Jackson 以便它可以为我完成,因为我的大部分输入/输出都通过 Jackson

我正在这三个选项中的任何一个中寻找 SpringMVC 的一些示例配置,并优先选择选项 B 和 C。

4

1 回答 1

5

在读取 JSON 时,这在属性(如属性)setTitle()的设置器中是最容易做到的。title

或者,如果您正在考虑转义其他字符(例如,防止嵌入 HTML 标记),请查看此博客条目:使用 Jackson 转义 JSON 中的 HTML 字符

于 2012-09-23T01:12:57.473 回答