MongoDBへ利用者を登録し、ログイン後に自分の情報を取得するローカルAPIを作ります。Express 5・Mongoose 9を対象に、入力検証、パスワードのハッシュ化、JWTの発行と検証、接続失敗時の処理を一つの例にそろえます。
更新:2026年10月26日。公開済みの固定秘密鍵、ログイン入力の検証不足、古いDB接続オプションを修正しました。
これは学習用です。ブラウザ向けのCookie設定、更新トークン、ログアウト時の即時失効、パスワード再設定、多要素認証は実装しません。専用の練習用DBを使い、実際の顧客情報や普段使うパスワードを入力しないでください。そのままインターネットへ公開するための完成品ではありません。
登録・ログイン・情報取得の流れ
- 登録:入力の型と長さを確認し、パスワードをハッシュ化してDBへ保存する。
- ログイン:入力を検証し、保存したハッシュと照合する。成功したときだけJWTを返す。
- API利用:署名・発行者・宛先・期限・用途を検証する。
- 利用者確認:トークン内の利用者がDBに存在するか確かめ、自分の情報だけを返す。
図1:入力検証、本人確認、JWT検証、操作の許可は、それぞれ別の段階です。
準備するもの
Node.js 22系以降と、ローカルで動作するMongoDBを用意します。MongoDBの導入は公式手順を参照し、DBのポートをインターネットへ公開しないでください。例では新しい練習用DBとしてauth_learningを使います。
mkdir node-auth-learning
cd node-auth-learning
npm init -y
npm install express@5 mongoose@9 jsonwebtoken@9 bcryptjs@3 express-rate-limit@8
node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
最後に生成した64桁の16進文字列を、作業フォルダーの.envに設定します。次の説明文をそのまま鍵として使わないでください。
MONGODB_URI=mongodb://127.0.0.1:27017/auth_learning
JWT_SECRET_HEX=自分で生成した64桁の16進文字列
.gitignoreには.envとnode_modules/を追加します。.envは平文なので、共有・バックアップ先にも注意します。秘密鍵がない場合は公開された固定値で代用せず、起動を止める設計にします。
server.cjsのコード
ユーザー名は英小文字・数字・アンダースコアで3〜32文字です。学習例のパスワード入力はJavaScriptのlengthで15〜64、さらにUTF-8で72バイト以内に限定します。bcryptには72バイトの制限があるため、文字数とバイト数を混同しません。パスワードはtrimや小文字化をしません。
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { rateLimit } = require('express-rate-limit');
const { randomBytes } = require('node:crypto');
const uri = process.env.MONGODB_URI;
const hex = process.env.JWT_SECRET_HEX;
if (!uri || typeof hex !== 'string' || !/^[0-9a-f]{64}$/i.test(hex)) {
throw new Error('MONGODB_URIと32バイトのJWT_SECRET_HEXを設定してください');
}
const key = Buffer.from(hex, 'hex');
const issuer = 'local-demo-auth';
const audience = 'local-demo-api';
const app = express();
app.use((req, res, next) => {
res.set('Cache-Control', 'no-store');
next();
});
app.use(express.json({ limit: '16kb' }));
app.use('/auth', rateLimit({
windowMs: 15 * 60 * 1000,
limit: 20,
standardHeaders: true,
legacyHeaders: false
}));
const User = mongoose.model('User', new mongoose.Schema({
username: { type: String, required: true, unique: true },
passwordHash: { type: String, required: true, select: false }
}));
let dummyHash;
function credentials(body) {
if (!body || typeof body.username !== 'string' || typeof body.password !== 'string') return null;
const username = body.username.trim().toLowerCase();
const password = body.password;
if (!/^[a-z0-9_]{3,32}$/.test(username)) return null;
if (password.length < 15 || password.length > 64 || Buffer.byteLength(password, 'utf8') > 72) return null;
return { username, password };
}
function unauthorized(res) {
return res.set('WWW-Authenticate', 'Bearer').status(401).json({ error: '認証に失敗しました' });
}
app.post('/auth/signup', async (req, res) => {
const input = credentials(req.body);
if (!input) return res.status(400).json({ error: '入力形式を確認してください' });
const passwordHash = await bcrypt.hash(input.password, 12);
const user = await User.create({ username: input.username, passwordHash });
return res.status(201).json({ id: String(user._id), username: user.username });
});
app.post('/auth/login', async (req, res) => {
const input = credentials(req.body);
if (!input) return unauthorized(res);
const user = await User.findOne({ username: input.username }).select('+passwordHash');
const matches = await bcrypt.compare(input.password, user ? user.passwordHash : dummyHash);
if (!user || !matches) return unauthorized(res);
const token = jwt.sign({ purpose: 'access' }, key, {
algorithm: 'HS256', subject: String(user._id), issuer, audience, expiresIn: '15m'
});
return res.json({ accessToken: token, tokenType: 'Bearer', expiresIn: 900 });
});
function authenticate(req, res, next) {
const header = req.get('authorization') || '';
if (header.length > 4096) return unauthorized(res);
const match = /^Bearer ([^\s]+)$/i.exec(header);
if (!match) return unauthorized(res);
try {
const claims = jwt.verify(match[1], key, { algorithms: ['HS256'], issuer, audience });
if (typeof claims !== 'object' || claims === null ||
typeof claims.sub !== 'string' || !/^[0-9a-f]{24}$/i.test(claims.sub) ||
typeof claims.exp !== 'number' || claims.purpose !== 'access') {
return unauthorized(res);
}
req.authSubject = claims.sub;
} catch {
return unauthorized(res);
}
next();
}
app.get('/me', authenticate, async (req, res) => {
const user = await User.findById(req.authSubject).select('username').lean();
if (!user) return unauthorized(res);
return res.json({ id: String(user._id), username: user.username });
});
app.use((req, res) => res.status(404).json({ error: 'URLが見つかりません' }));
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
if (err.type === 'entity.parse.failed') return res.status(400).json({ error: 'JSONが不正です' });
if (err.type === 'entity.too.large') return res.status(413).json({ error: '本文が大きすぎます' });
if (err.code === 11000) return res.status(409).json({ error: 'そのユーザー名では登録できません' });
if (err.name === 'ValidationError') return res.status(400).json({ error: '入力形式を確認してください' });
console.error('Request failed:', err.name);
return res.status(500).json({ error: '内部エラーです' });
});
async function start() {
await mongoose.connect(uri, { serverSelectionTimeoutMS: 5000 });
await User.init();
dummyHash = await bcrypt.hash(randomBytes(24).toString('hex'), 12);
const server = app.listen(3000, '127.0.0.1', () => console.log('http://127.0.0.1:3000'));
server.on('error', async (err) => {
console.error('Listen failed:', err.code);
await mongoose.disconnect();
process.exitCode = 1;
});
}
start().catch(async (err) => {
console.error('Startup failed:', err.name);
await mongoose.disconnect();
process.exitCode = 1;
});
動作を確かめる
node --env-file=.env server.cjs
APIクライアントでhttp://127.0.0.1:3000を対象に操作します。POSTの本文形式はJSON、Content-Typeはapplication/jsonです。登録とログインでは同じusernameとpasswordを送ります。練習用のパスワードは自分で用意してください。
| メソッドとURL | 送るもの | 期待する応答 |
|---|
| POST /auth/signup | usernameとpasswordの文字列。 | 201と利用者ID・ユーザー名。 |
| POST /auth/login | 登録したusernameとpassword。 | 200とaccessToken。 |
| GET /me | Authorization: Bearer の後へ取得したトークン。 | 200と自分のID・ユーザー名。 |
| GET /me(トークンなし) | なし。 | 401。 |
| 重複するユーザー名で登録 | 既存と同じusername。 | 409。 |
| 壊れたJSON・長すぎる本文 | 不正な本文。 | 400または413。 |
15分間に認証関連リクエストが20回を超えると、同じ接続元からの操作は制限されます。これは1プロセス内の簡易設定であり、実サービスではプロキシ構成、共有ストア、アカウント単位の制御も検討します。
旧版から修正した重要点
DB接続が成功する前にAPIを公開しません。接続をawaitし、練習用の一意インデックスを準備してから待ち受けを始めます。古いuseNewUrlParser・useUnifiedTopologyは付けません。接続とバージョン差はConnectionsとMongoose 9移行ガイドを参照してください。
入力の値を確認してからDBへ渡します。ログイン時も文字列かを検査し、クライアントから来たオブジェクトを検索条件へそのまま渡しません。uniqueは通常の入力バリデーターではなく、一意インデックスに関わる設定です。重複エラーは別に処理します。
署名だけでなく用途も照合します。JWTは15分で期限切れにし、検証側でHS256・発行者・宛先を固定します。パスワードやハッシュはトークンと応答へ含めません。詳細はjsonwebtokenの開発元資料、パスワードの制限はbcrypt.jsの資料に対応しています。
本番用にする場合の追加設計
HTTPS、秘密情報の管理と鍵更新、パスワード保存方式の選定、漏えい済みパスワードへの対策、アカウント保護、即時失効、更新トークン、データごとの認可、DBのバックアップなどが必要です。ブラウザの保存方式も別途設計し、ここで返したJWTを安易にlocalStorageへ保存しません。ログアウトの即時失効機能は、この例にはありません。
関連:JWTの保存方法と検証の考え方/Express 5のルーティングとエラー処理。公式資料:Mongoose Validation/express-rate-limit。