본문 바로가기
Q&A2022년 5월 14일1분 읽기

XSS 방어용 DOMPurify 사용법

엄
엄태준
조회 392댓글 3

React에서 dangerouslySetInnerHTML을 써야 하는데 XSS가 걱정됩니다. DOMPurify를 어떻게 쓰나요?

댓글 3

김김영삼4년 전

DOMPurify로 HTML 정제하는 방법:

import DOMPurify from "dompurify";

// 기본 사용
const clean = DOMPurify.sanitize(dirtyHTML);

// React에서
function SafeHTML({ html }: { html: string }) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['p', 'b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li',
'h1', 'h2', 'h3', 'pre', 'code', 'blockquote', 'img', 'br'],
ALLOWED_ATTR: ['href', 'src', 'alt', 'class', 'target'],
});
return
;
}

DOMPurify가 제거하는 것:

  • <script> 태그
  • 이벤트 핸들러 (onclick, onerror 등)
  • javascript: URL
  • data: URL (이미지 제외)

사용자가 작성한 HTML을 렌더링할 때는 반드시 DOMPurify를 거쳐야 합니다.

나나윤아(guest)4년 전
많이 배웠습니다. 감사해요.
오오수빈(guest)4년 전
자세한 설명 감사합니다.
Ctrl+Enter로 등록