본문 바로가기
웹개발/node.js

웹페이지 입출력 보안. sanitizehtml로

by 육만 2021. 1. 29.

생활코딩 node.js 강의도 거의 다 들었다.

 

이번엔 보안에 관한 내용을 배웠다.

 

 

먼저,

cmd창에서 워킹스페이스 폴더 위치로 놓고

npm init

을 하면 package.json이 생성된다.

 

npm install -S sanitize-html

을 입력.

 

 

sanitize-html 모듈이 설치된다.

 

 

main.js 상단에

var sanitizeHtml = require('sanitize-html');

선언.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
else {
        fs.readdir('./data'function(error, filelist) {
        var filteredId = path.parse(queryData.id).base;
        fs.readFile(`data/${filteredId}`, 'utf-8'function(err, description) {
        var title = queryData.id;
        var list = template.list(filelist);
        var sanitizedTitle = sanitizeHtml(title);
        var sanitizedDescription = sanitizeHtml(description, {
          allowedTags:['h1']
        });
        var html = template.html(sanitizedTitle, list, 
`<h2>${sanitizedTitle}</h2><br>${sanitizedDescription}`,
        `<a href="/create">글쓰기</a>
        <a href="/update?id=${title}">글수정</a>
        <form action="/delete_process" method="post" onsubmit=function() {
          var answer = confirm("정말 삭제하시나요?");
          if(answer==true) {
            this.action = ""
          }else {
            this.action = "/."
          }
        }>
          <input type='hidden' name='id' value='${sanitizedTitle}'>
          <input type='submit' value='글삭제'>
        </form>
        `);
        response.writeHead(200);
        response.end(html);
      });
    });
  }
cs

sanitize-html은

사용자의 악성 코드 공격을 차단하는 모듈이다.

 

 

사용자에게 입력을 받을 때,

자바스크립트 코드나 html 코드로

공격을 받을 수 있다.

 

 

이걸 무력화하는 모듈이기 때문에

보안 유지에 중요하다.

 

 

sanitizehtml(title);

이런 식으로 쓰면 입력 받은 값을

소독해준다.

 

만약, <h1>과 같은 위험하지 않은 코드를

허용해주고 싶다면

sanitizeHtml의 두번째 인자로

allowedTags:['허용하고싶은태그']

이런 식으로 처리할 수 있다.

 

 

댓글