DEV Community

Cover image for DOMPurify,增加網站對 XSS 攻擊的防護力
Let's Write
Let's Write

Posted on • Edited on • Originally published at letswrite.tw

DOMPurify,增加網站對 XSS 攻擊的防護力

本篇要解決的問題

最近看了胡立大大的〈Beyond XSS:探索網頁前端資安宇宙〉(推薦前端工程師必看),才發現之前寫程式時很少注意到會不會容易被人攻擊這塊。

記得很久很久以前,久到 Firebase 還沒被 Google 併購以前,那時寫了一個送出表單後,會在頁面上變成賀卡的功能,就有人寫上了 <script>alert(false)</script> 在測試,然後好心的回覆說這個表單功能是會被攻擊的,也是那次以後才知道原來一不注意,input 可以被寫入程式碼。

本篇推薦使用的 DOMPurify,就是一個可以防範這種問題的套件,也是在胡立大大的文章裡知道的,本篇只會提供使用範例,詳細解說請點擊上面的連結。

本篇提供的 Demo:

https://letswritetw.github.io/letswrite-dompurify/


安裝

DOMPurify 的官方說明文件:cure53/DOMPurify

CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

ES6

// 先執行命令進行安裝
$ npm install dompurify

// JS 檔案中 import
import * as DOMPurify from 'dompurify';
Enter fullscreen mode Exit fullscreen mode

使用

使用的時機點有蠻多的,比方從網址上抓出參數後、從 API 取回資料、表單要送出前,都可以使用,防止收到攻擊性的語法。

DOMPurify 使用的方式也很簡單,就一行:

const clean = DOMPurify.sanitize(要處理的值);
Enter fullscreen mode Exit fullscreen mode

比方我們有一個 input:

<input type="text" id="userName">
Enter fullscreen mode Exit fullscreen mode

要送給後端時,就先用 DOMPurify 處理過一次:

const input = document.getElementById('userName');
const userName = DOMPurify.sanitize(input.value);
Enter fullscreen mode Exit fullscreen mode

最後再把 userName 送出去,安全上會多一層保障。


Demo 及原始碼

本篇的 Demo 及原始碼都放在 GitHub 上了。

Demo 主要是輸入值以後,會看到 DOMPurify 執行後的結果。

Demo:https://letswritetw.github.io/letswrite-dompurify/

原始碼:https://github.com/letswritetw/letswrite-dompurify

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay