mkcert라는 프로그램을 이용해서 로컬 환경(내 컴퓨터)에서 신뢰할 수 있는 인증서를 만들 수 있습니다.
Homebrew를 통해 mkcert를 설치하기
$ brew install mkcert
인증서 생성하기
$ brew install nss
로컬을 인증된 발급기관으로 추가하기
$ mkcert -install
로컬 환경에 대한 인증서를 만들기
(localhost로 대표되는 로컬 환경에 대한 인증서를 만들려면 아래의 명령어 입력)
$ mkcert -key-file key.pem -cert-file cert.pem localhost 127.0.0.1 ::1
이제 옵션으로 추가한 localhost, 127.0.0.1(IPv4), ::1(IPv6)에서 사용할 수 있는 인증서가 완성되었습니다. cert.pem, key.pem 이라는 파일이 생성된 것을 확인할 수 있습니다.
여기서 발급받은 key와 cert를 앞으로 쿠키, 세션, 토큰 스프린트에서 계속 활용하게 됩니다. 저장 경로를 반드시 확인하세요.
인증서는 공개키, 그리고 인증기관의 서명을 포함하고 있으므로 공개되어도 상관이 없지만, key.pem의 경우 개인 키이므로 git에 커밋하지 않고, 암호처럼 다루어야 합니다.
질문: key와 cert의 다른 점은 무엇일까요?
Ubuntu
우분투의 경우 다음 명령어를 이용해 설치합니다.
$ sudo apt install libnss3-tools
$ wget -O mkcert https://github.com/FiloSottile/mkcert/releases/download/v1.4.3/mkcert-v1.4.3-linux-amd64
$ chmod +x mkcert
$ sudo cp mkcert /usr/local/bin/
Node.js 환경에서 HTTPS 서버를 작성하기 위해서는 https 내장 모듈을 이용할 수 있습니다. express.js를 이용해 https 서버를 만들 수도 있습니다.
먼저는 방금 생성한 인증서 파일들을 HTTPS 서버에 적용해 주는 작업이 필요합니다.
Node.js https 모듈 이용
const https = require('https');
const fs = require('fs');
https
.createServer(
{
key: fs.readFileSync(__dirname + '/key.pem', 'utf-8'),
cert: fs.readFileSync(__dirname + '/cert.pem', 'utf-8'),
},
function (req, res) {
res.write('Congrats! You made https server now :)');
res.end();
}
)
.listen(3001);
이제 서버를 실행한 후 https://localhost:3001로 접속하시면 브라우저의 url 창 왼쪽에 자물쇠가 잠겨있는 HTTPS 프로토콜을 이용한다는 것을 알 수 있습니다!
만약 express.js 를 사용하는 경우, 다음과 같이 https.createServer의 두 번째 파라미터에 들어갈 callback 함수를 Express 미들웨어로 교체하면 그만입니다!
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();
https
.createServer(
{
key: fs.readFileSync(__dirname + '/key.pem', 'utf-8'),
cert: fs.readFileSync(__dirname + '/cert.pem', 'utf-8'),
},
app.use('/', (req, res) => {
res.send('Congrats! You made https server now :)');
})
)
.listen(3001);
코드스테이츠