為了避免XSS攻擊, 也就是https://en.wikipedia.org/wiki/Cross-site_scripting

網站內的script會破壞頁面的擷取或是有惡意的行為

所以jsout提供了whitelist白名單的方法來處理

介紹如下

 

1. 官網https://jsoup.org/cookbook/cleaning-html/whitelist-sanitizer

01.png

 

2. 基本語法

Jsoup.clean(html來源, 白名單類型)

如果要自訂的話則自己宣告一個Whitelist

然後用.add("允許類型")來增加

範例如下

String unsafe = "<p><a href='http://example.com/' "
    + "onclick='stealCookies()'>Link</a></p>"
    + "<c>This is b</c>";
  
  System.out.println( Jsoup.clean(unsafe, Whitelist.none()));
  //LinkThis is b
  
  System.out.println( Jsoup.clean(unsafe, Whitelist.basic()));
  //<p><a href="http://example.com/" rel="nofollow">Link</a></p>This is b
  
  Whitelist whitelist = new Whitelist();
  whitelist.addTags("c");
  System.out.println( Jsoup.clean(unsafe, whitelist));
  //Link<c>This is b</c>

02.png

3. 其他常用的方法

Whitelist.none() :只允許包含文本信息
  
Whitelist.basic() :允許的標籤包括:a, b, blockquote, br, cite, code, 
dd, dl, dt, em, i, li, ol, p, pre, q, small, strike, 
strong, sub, sup, u, ul , 以及合適的屬性
  
Whitelist.simpleText() :允許b, em, i, strong, u 這些標籤
  
Whitelist.basicWithImages() 在basic() 上多了圖片
  
Whitelist.relaxed() 允許 :a, b, blockquote, br, caption, 
cite, code, col, colgroup, dd, dl, dt, em, h1, h2, h3, h4, 
h5, h6, i, img, li, ol, p, pre, q, small, strike, strong, 
sub, sup, table, tbody, td, tfoot, th, thead, tr, u, ul

03.png  

arrow
arrow

    RX1226 發表在 痞客邦 留言(0) 人氣()