HTML-Entity escaping to prevent XSS

前端 未结 2 688
一整个雨季
一整个雨季 2021-02-02 17:44

I have some user input. Within my code, I ensure that the following symbols are escaped:

& -> & 
< -> < 
> -> >
<         


        
2条回答
  •  情话喂你
    2021-02-02 17:55

    I use the OWASP (ESAPI) library as well, to escape strings for different types of display, use :

    String html = ESAPI.encoder().encodeForHTML("hello < how > are 'you'");
    String html_attr = ESAPI.encoder().encodeForHTMLAttribute("hello < how > are 'you'");
    String js = ESAPI.encoder().encodeForJavaScript("hello < how > are 'you'");
    

    HTML (assume jsp)

    <%= html %>
    

    Update (2017)

    As ESAPI Encoders are considered legacy, a better alternative has been created and is actively being maintained, I would strongly recommend using the OWASP Java Encoder instead.

    If your project already uses ESAPI, an integration has been added that will allow you to use this library for encoding instead.

    The usage is explained on their wiki page, but for the sake of completion, this is how you can use it to contextually encode your data:

    // HTML Context
    String html = Encoder.forHtml("ute'd'");
    
    // HTML Attribute Context
    String htmlAttr = Encoder.forHtmlAttribute("ute'd'");
    
    // Javascript Attribute Context
    String jsAttr = Encoder.forJavaScriptAttribute("ute'd'");
    

    HTML (assume jsp)

    <%= html %>

    PS: more contexts exist and are supported by the library

提交回复
热议问题