Koaで構築したサーバをHTTPS/HTTP2化する
Koa とは
Node.js 用の Web フレームワークです
Node.js 用の Web フレームワークと言えば express が有名ですが、そのメンバーが作っているようです
Generator が使えるのが特徴です
サンプル
公式サイトにあるサンプルソースです
const koa = require('koa');
const app = koa();
app.use(function *(){
this.body = 'Hello World';
});
app.listen(3000);
node app.js
を実行し、「 http://localhost:3000 」にアクセスすると
このように「Hello World」が表示される
このサンプルを HTTPS/HTTP2化 していきたいと思います
証明書の作成
今回はローカル環境を対象にしますので、オレオレ証明書でいきます
OpenSSL がインストールされていることが前提です
秘密鍵の作成
openssl genrsa 2048 > server.key
# 秘密鍵をパスフレーズで保護する場合、暗号化するためのオプションを追加する
# -des, -des3, -aes128, -aes192, -aes256 等が選択可能
CSR(証明書の基になる情報)の作成
openssl req -new -sha256 -key server.key -out server.csr
証明書の署名アルゴリズムに SHA-1 を使っている場合、2017年以降通信できなくなるので
-sha256
を指定する
証明書(公開鍵)の作成
openssl x509 -in server.csr -out server.crt -req -signkey server.key -sha256 -days 3650
-days
で証明書の有効期限を設定します
オレオレなので10年にしました
HTTPS化
HTTPS化する場合は、すでにモジュールが Node.js に組み込まれているので前準備は必要ありません
const koa = require('koa');
const app = koa();
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('server.key'), // 作成した秘密鍵のパスを指定し読み込む
cert: fs.readFileSync('server.crt') // 作成した証明書のパスを指定し読み込む
};
app.use(function *(){
this.body = 'Hello World';
});
https.createServer(options, app.callback()).listen(3000);
app.callback()
を呼ぶと createServer
に渡す callback を返してくれます
また、秘密鍵をパスフレーズで保護している場合は下記のように指定します
const options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt'),
passphrase: '秘密鍵作成時に指定したパスフレーズ'
};
node app.js
を実行し、「 https://localhost:3000 」にアクセスすると
https 接続できていることがわかります
HTTP2化
基本は HTTPS と同じですが、http2
モジュールのインストールが必要です
npm install http2
これで準備完了です
const koa = require('koa');
const app = koa();
const http2 = require('http2');
const fs = require('fs');
const options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
app.use(function *(){
this.body = 'Hello World';
});
http2.createServer(options, app.callback()).listen(3000);
https
の部分が http2
に変わっただけですね
node app.js
を実行し、「 https://localhost:3000 」にアクセスし、Developer Tools で確認すると
http2 接続できていることがわかります
Author And Source
この問題について(Koaで構築したサーバをHTTPS/HTTP2化する), 我々は、より多くの情報をここで見つけました https://qiita.com/y_fujieda/items/9998f28e702dc7c84473著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .