mkcer でローカル環境へオレオレ認証局とオレオレ証明書を作成し Node.js の Express サーバーを SSL(https)で起動する手順

Node.jsインストールexpressセキュリティー
mkcer でローカル環境へオレオレ認証局とオレオレ証明書を作成し Node.js の Express サーバーを SSL(https)で起動する手順
Memo
この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

mkcer でローカル環境へオレオレ認証局とオレオレ証明書を作成し Node.js の Express サーバーを SSL(https)で起動する手順をメモしました。

経緯

商用環境は SSL での運用が必要なため、開発環境も SSL できると何かと便利だったため
SSL でローカル環境を起動できるようにしたかったたため手順を整理しました。

mkcert

mkcert とは?

SSL の自己証明書を自動で作成してくれるツールになります。 自己証明書を作る手順は複雑で何かと時間がかかる作業なのですがその辺を自動でやってくれるため
シンプルでお手軽に発行することができます。

Github

mkcert | Github

やること

環境

  • Mac OS Big SUR 11.3.1
  • yarn 1.22.10
  • Node 14.15.3
  • express 4.17.1

ファイル操作で利用する Unix コマンドについて

基本的なディレクトリ作成やファイル操作は Unix コマンドを利用します。
Unix コマンドについて詳しくはこちらの記事を参考にしてください。

事前準備

Homebrew が必要

Homebrewを先にインストールする必要があります。
インストール手順については下記の記事を参照ください。

Homebrew のインストール

Node.js 環境が必要

事前準備として Node.js が利用できる環境で実施します。
Node.js の環境の構築について詳しくはこちらの記事を参考にしてください。

yarn コマンドのインストール

事前準備として Yarn が利用できる環境で実施します。
Yarn コマンドのインストールについて詳しくはこちらの記事を参考にしてください。

TypeScript 環境で実施

事前準備として TypeScript が利用できる環境で実施します。
TypeScript の実行環境の構築について詳しくはこちらの記事を参考にしてください。

SSLサンプルプロジェクトの作成

プロジェクトディレクトリを作成

~/ssl-sampleというプロジェクトディレクトリを作成します。

terminal
$ mkdir ~/ssl-sample

プロジェクトディレクトリへ移動

作成した~/ssl-sample ディレクトリへ移動します。

terminal
$ cd ~/ssl-sample

オレオレ認証局とオレオレ証明書を作成

Homebrew で mkcert をインストール

Homebrew のbrewコマンドで mkcert をインストールします。

terminal
$ brew install mkcert

mkcert のインストールを確認

mkcert --versionコマンドでバージョンを確認しインストールが出来たか確認します。

terminal
$ mkcert --version v1.4.3

Firefox で使うなら nss もインストール

Firefox で使うなら nss もインストールします。

terminal
$ brew install nss

ローカルに認証局を作成

ローカルにオレオレ認証局を作成します。

terminal
$ mkcert -install Using the local CA at "/Users/kakakakakku/Library/Application Support/mkcert" ✨ The local CA is now installed in the system trust store! ⚡️

オレオレ証明書の作成

オレオレ証明書の作成します。
今回は https://ssl-sample.comでアクセスできるようにしたいと思います。
作成する証明書は ssl-sample.com*.ssl-sample.comlocalhost127.0.0.1 を作成しサブドメインや localhost でも利用できるようにします。

terminal
$ mkcert ssl-sample.com "*.ssl-sample.com" localhost "127.0.0.1" Created a new certificate valid for the following names 📜 - "ssl-sample.com" - "*.ssl-sample.com" - "localhost" - "127.0.0.1" Reminder: X.509 wildcards only go one level deep, so this won't match a.b.ssl-sample.com ℹ️ The certificate is at "./ssl-sample.com+3.pem" and the key at "./ssl-sample.com+3-key.pem" ✅ It will expire on 2 October 2023 🗓

作成された証明書を確認

証明書が作成されるので確認します。

terminal
$ ls ssl-sample.com+3-key.pem ssl-sample.com+3.pem

ローカル開発環境へNode.jsのExpressサーバーを構築

yarn を初期化をして package.json を作成

yarn でプロジェクトの初期化を行います。
npm で実施する方は必要に応じて変更してください。

terminal
$ yarn init -y yarn init v1.22.10 warning The yes flag has been set. This will automatically answer yes to all questions, which may have security implications. success Saved package.json ✨ Done in 0.08s.

必要なパッケージのインストール

必要なパッケージ

experss と TypeScript のパッケージをインストールします。

  • express
  • https
  • @types/express
  • typescript
  • @types/node
  • ts-node

パッケージのインストール

yarn addコマンドで必要パッケージをインストールします。

terminal
$ yarn add express https

開発に関連するパッケージのため -Dオプションを付与しています。

$ yarn add -D ts-node @types/express typescript @types/node

インストールしたパッケージを確認

package.json を開きインストールされたパッケージを確認します。

  "devDependencies": {
    "@types/express": "^4.17.12",
    "@types/node": "^15.12.5",
    "ts-node": "^10.0.0",
    "typescript": "^4.3.4"
  },
  "dependencies": {
    "express": "^4.17.1",
    "https": "^1.0.0"
  }

tsconfig.json を作成

プロジェクトルートへ tsconfig.json を作成します。

terminal
$ vi tsconfig.json

tsconfig.json の設定例

tsconfig.json
{ "compilerOptions": { "target": "es2020", "module": "commonjs", "lib": [ "es2020" ], "sourceMap": true, "outDir": "./dist", "rootDir": "./src", "strict": true, "moduleResolution": "node", "baseUrl": "src", "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": [ "src/**/*" ], "exclude": [ "dist", "node_modules" ], "compileOnSave": false }

ts-config のオプションはこちらの記事を参考にしてください

ソースディレクトリの作成

プロジェクトルートへsrcディレクトリを作成します。

terminal
$ mkdir src

アプリケーションのファイルを作成

作成したソースディレクトリへ index.ts を追加します。

terminal
$ vi src/index.ts

express をインポート

import 文で express をインポートします。

src/index.ts
import express from 'express';

express の初期化

import した express を呼び出して express を初期化します。

src/index.ts
const app = express();

トップページの作成

トップページを作成します。
とりあえず Hello というメッセージを表示させます。

src/index.ts
app.get( '/', (_req: express.Request, res: express.Response): void => { res.send('Hello'); } );

その他

その他のリクエストの処理になります。

ステータスコードを 404 に指定してレスポンスを返してます。

src/index.ts
app.all('*', (_req: express.Request, res: express.Response): void => { res.status(404).json({}); });

証明証の設定

先ほど作成した証明書を読み込みます。 ポート 8080 でリクエストを待ち受ける処理になります。

src/index.ts
const options = { key: fs.readFileSync( path.resolve(__dirname, `../ssl-sample.com+3-key.pem`) ), cert: fs.readFileSync( path.resolve(__dirname, `../ssl-sample.com+3.pem`) ), };

src/index.ts 全体

上記の設定含めた全体のソースコードになります。

src/index.ts
import express from 'express'; import https from 'https'; import fs from 'fs'; import path from 'path'; const app = express(); app.use(express.json()); app.get( '/', (_req: express.Request, res: express.Response): void => { res.send('Hello'); } ); app.all( '*', (_req: express.Request, res: express.Response): void => { res.status(404).json({}); } ); const options = { key: fs.readFileSync( path.resolve(__dirname, `../ssl-sample.com+3-key.pem`) ), cert: fs.readFileSync( path.resolve(__dirname, `../ssl-sample.com+3.pem`) ), };

SSLのアクセス確認

Express アプリケーションを起動

アプリケーションを起動させていきます。

npm scripts へ起動コマンドの追加

実行するコマンドを追記します。

package.json

package.json
"scripts": { "start": "node dist/index.js", "build": "tsc", "dev": "ts-node src/index.ts" },

dev でアプリサーバーを起動

yarn devコマンドを実行します。

terminal
$ yarn dev yarn run v1.22.10 $ ts-node src/index.ts listening on *:8080

8080 で待ち受ける形でアプリケーションが起動しました。

hostsの追加

設定したドメインでアクセスした際にローカルホストを見るように設定を変更します。

$ sudo vi /etc/hosts
127.0.0.1       localhost ssl-sample.com hoge.ssl-sample.com

ブラウザからアクセス

それぞれのドメインへブラウザからアクセスして確認します。

ローカルホストへのアクセス

localhost:8080へのアクセス

ブラウザからアクセス localhost:8080

一般ドメインへのアクセス

ssl-sample.com:8080へのアクセス

ブラウザからアクセス ssl-sample.com:8080

サブドメインへのアクセス

hoge.ssl-sample.com:8080へのアクセス

ブラウザからアクセス hoge.ssl-sample.com:8080

SSL(https)からアクセスすることができました。

オレオレ証明証の確認

証明証も読み込まれています。

オレオレ証明証の確認

終わりに

最後までご覧いただきありがとうございます。
この記事ではmkcer でローカル環境へオレオレ認証局とオレオレ証明書を作成し Node.js の Express サーバーを SSL(https)で起動する手順について紹介させていただきました。

これからも皆様の開発に役立つ情報を提供していきたいと考えています。
今後ともよろしくお願いいたします。