0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

nodejs SSLサーバ構築 チートシート

Last updated at Posted at 2020-06-25

説明はこちら
nodejs サーバ構築 チートシート

node SSLサーバ チートシート

構成

├ server.js
├ package.json # nodejs サーバ構築 チートシート と同じ
├ download.txt # ダウンロード用ファイル。中身はなんでもok
└ cert
 ├ server.cnf
 ├ server.crt
 └ server.key

server.js
'use strict';
var log4js = require('log4js');
var logger = log4js.getLogger('test');
log4js.configure({ appenders: { default: { type: "console", layout: { type: "basic" } } }, categories: { default: { appenders: ['default'], level: 'debug' }}, replaceConsole: true, level: 'info' })
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var https = require('https');
var fs = require('fs');
var options = {
  key:  fs.readFileSync(__dirname +'/cert/server.key'),
  cert: fs.readFileSync(__dirname +'/cert/server.crt')
};
var util = require('util');
var host = 'localhost'; 
var port = 8443;

app.use( function(req,res,next) {
	logger.info('%s %s', req.method, req.url);
	logger.info('header='+JSON.stringify(req.headers));
	logger.info('query='+JSON.stringify(req.query));
	logger.info('body='+JSON.stringify(req.body));
	next();
});

var server = https.createServer(options,app).listen(port, function() {});
console.log('*** server start https://%s:%s ***',host,port);
logger.info('*** server start https://%s:%s ***',host,port);
server.timeout = 30000;
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0; // オレオレ証明書サーバへリクエストする場合

// top page
app.all('/', function(req, res) { // methodを限定しない
	res.header({'Content-type': 'text/html'});
	res.end(util.format('<h1>http://%s:%s for honya</h1>',host,port)); // サーバの用途が分かるようなタイトルを表示する
});

// json を返す場合 REST形式
app.all('/rest/v1/user/:id', function(req,res) { 
	logger.info('id='+req.params.id); // url パラメータの参照

	let json = {
		id: req.params.id,
		name: "honya",
		dob: (new Date('2020-01-01 12:34:56')).getTime(),
	}
	res.status(201).json(json);
});

// html を返す場合 ASP.NET形式
app.all('/asp/honya.asmx', function(req,res) {
	let html = `
<html>
<body>
	<h1>request url: ${req.method} ${req.url}</h1>
	<div>response</div>
</body>
</html>
`;
	res.end(html); 
});

// 存在するファイルをダウンロードする場合 cgi形式
app.all('/cgi-bin/honya.cgi', function(req,res) { 
	res.download(__dirname + '/download.txt','server.log'); 
});

// csvデータをダウンロードする場合 php形式
app.all('/php/honya.php', function(req,res) { 
	let header = {
		'Content-disposition': 'attachment; filename=server.csv',
		'Content-type': 'text/plain; charset=utf-8',
	}
	res.header(header);

	let csv = "id,name\n1,honya\n";
	res.send(csv); 
});
server.cnf
[req]
distinguished_name = req_distinguished_name
x509_extensions = SAN
prompt = no

[req_distinguished_name]
C = Country initials like US, RO, GE
ST = State
L = Location
O = Organization Name
OU = Organizational Unit 
CN = localhost

[SAN]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost

server.crt と server.key はコマンドで作成

cd ~/cert # 証明書フォルダへ移動
openssl req \
  -newkey     rsa:4096 \
  -keyout     server.key \
  -x509 \
  -nodes \
  -out        server.crt \
  -subj       "//CN=localhost" \
  -days       3650 \
  -reqexts    SAN \
  -extensions SAN \
  -config     server.cnf

起動

nodejs サーバ構築 チートシート と同じ

常時起動

nodejs サーバ構築 チートシート と同じ

localhost SSL証明書

参考

証明書の取り込みは以下のStep 6.を参照
create a trusted self-signed SSL cert for localhost
※取り込んだあと、ブラウザの再起動をお忘れなく σ(゚∀゚ )オレ

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?