NodeJS - 로컬서버에 HTTPS 적용하기 with OpenSSL

DW J·2022년 8월 23일
0

develop_wis

목록 보기
5/9
post-thumbnail

개인 프로젝트를 진행하면서 요구사항으로 로컬서버의 http를 https로 변경해야 하는데 방법을 찾아 적용해보고 기록을 남기면 좋을것 같아 작성하게 된 글입니다.

Node JS에서 HTTPS 적용하는 방법

  1. SSL인증서 다운 및 설정
  2. Node JS에서 HTTP > HTTPS적용

1. SSL인증서 다운 및 설정

로컬에서 https를 적용하기 때문에 인증기관의 인증서가 아닌 직접 인증서를 생성

OpenSSL 다운 및 설정 블로그 바로가기 (블로그 참고)


2. Node JS에서 HTTP > HTTPS적용

SSL인증서 다운 후 설정을 완료가 되었다면 인증서 파일을 생성

인증서 생성하는 방법

  1. cmd를 관리자모드로 실행하고 nodejs가 설치되어 있는 경로로 이동

  2. cmd를 관리자 모드로 실행하여 복사해놓은 경로로 이동

  3. 그 상태에서 명령어를 입력하여 인증서 파일 임시로 생성

    cmd 명령어 - 인증서는 두개 필요 (private, public)

    1) private.pem 파일 생성 명령어
    openssl genrsa 1024

    2) public.pem 파일 생성 명령어
    openssl req -x509 -new -key private.pem

    위 명령어로 생성하고 나면 국가, 도시, 이름 등등 입력하는 내용이 나오는데
    아무거나 입력하셔도 됩니다

  4. 만들어진 파일을 내 로컬(서버) 폴더로 복사

  5. https로직 적용
    - http모듈 > https모듈로 변경
    - 생성한 파일 fs모듈로 가져오기 (path 사용)
    - createServer()에 첫번째 인자로 해당 파일 넘겨주기 객체형태 - { key:, cert: }
    ex) https.createServer(options, function () { ... })

https 적용 전

const http = require('http');
const defaultPort = 3030;

module.exports = {
    init: function (callback, port) {
        if (!callback) throw new Error('callback is not defined');

        this.callback = callback;
        this.port = port || defaultPort;
    },

    createServer: function () {
        http.createServer(this.callback)
            .listen(this.port, () => {
                console.log(`[Server] listening on port ${this.port}`);
            });
    }
}

https 적용 후
const https = require('https');
const fs = require('fs');
const path = require('path');
const defaultPort = 3030;

module.exports = {
    createServer: function () {
        https.createServer(this.getSSLOptions(), this.callback)
            .listen(this.port, () => {
                console.log(`[Server] listening on port ${this.port}`);
            });
    },

    getSSLOptions: function () {
        return {
            key: fs.readFileSync(path.resolve("./server/ssl/private.pem")),
            cert: fs.readFileSync(path.resolve("./server/ssl/public.pem"))
        }
    }
} 



참고
NodeJS HTTPS 적용 : https://rosypark.tistory.com/305

profile
잘하는것보다 꾸준히하는게 더 중요하다

0개의 댓글