jsonwebtoken、koa-jwt、koa-passport、passport-jwt は、すべて JSON Web Token (JWT) を扱いますが、役割と抽象化のレベルが異なります。jsonwebtoken は JWT の署名と検証を行う低レベルなコアライブラリです。koa-jwt は Koa フレームワーク専用のミドルウェアで、jsonwebtoken の機能をラップしています。passport-jwt は Passport.js エコシステム向けの JWT 認証戦略であり、koa-passport は Passport を Koa で動作させるためのアダプターです。これらを組み合わせることで、シンプルな認証から複雑なマルチ戦略認証まで実現できます。
JWT(JSON Web Token)を用いた認証は、現代の Web アプリケーションにおいて標準的な仕組みとなっています。しかし、実装方法にはいくつかの選択肢があり、それぞれに適したシナリオが異なります。jsonwebtoken、koa-jwt、koa-passport、passport-jwt の 4 つのパッケージは、一見すると同じ目的のために存在するように見えますが、実際には異なるレイヤーで動作します。
本稿では、これらのパッケージの技術的な違い、実装コスト、そして拡張性の観点から比較し、プロジェクトに最適な選択をするための指針を提供します。
認証フローの根幹となるのは、トークンの「発行(署名)」と「検証」です。この基本機能を提供しているのは jsonwebtoken だけです。他の 3 つは、この機能をラップしてミドルウェアとして提供しています。
jsonwebtoken
最も低レベルなライブラリです。HTTP リクエストの処理は行わず、純粋なトークン操作に特化しています。
const jwt = require('jsonwebtoken');
// トークンの発行
const token = jwt.sign({ userId: 123 }, 'SECRET_KEY', { expiresIn: '1h' });
// トークンの検証
try {
const decoded = jwt.verify(token, 'SECRET_KEY');
console.log(decoded.userId); // 123
} catch (err) {
console.error('Invalid token');
}
koa-jwt
内部で jsonwebtoken を使用していますが、Koa のミドルウェアとして動作します。リクエストヘッダーからのトークン抽出を自動で行います。
const jwt = require('koa-jwt');
// ミドルウェアとして設定
app.use(jwt({ secret: 'SECRET_KEY' }).unless({ path: ['/public'] }));
// 検証済みのユーザー情報は ctx.state.user に格納される
app.use(async (ctx) => {
ctx.body = ctx.state.user;
});
passport-jwt
Passport.js の「戦略(Strategy)」として機能します。単体では Koa や Express のミドルウェアにはならず、Passport の初期化プロセス内で定義されます。
const JwtStrategy = require('passport-jwt').Strategy;
// 戦略の定義
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'SECRET_KEY'
},
async (jwt_payload, done) => {
// ユーザー検索ロジック
const user = await findUser(jwt_payload.id);
return done(null, user);
}
));
koa-passport
Passport を Koa で動作させるためのアダプターです。passport-jwt で定義した戦略を、Koa のミドルウェアとして登録するために使用します。
const passport = require('koa-passport');
// Passport の初期化
app.use(passport.initialize());
// ルートでの認証
router.get('/profile', passport.authenticate('jwt', { session: false }), async (ctx) => {
ctx.body = ctx.state.user;
});
フレームワークとの統合方法は、開発体験(DX)に大きな影響を与えます。koa-jwt は Koa 専用に設計されているため非常にシンプルですが、passport-jwt + koa-passport の組み合わせは設定が複雑になる代わりに柔軟性を提供します。
koa-jwt:Koa ネイティブな統合
Koa のコンテキスト(ctx)に直接依存しているため、設定が最小限で済みます。Authorization ヘッダーの解析もデフォルトで処理されます。
// koa-jwt の場合
// 1. ミドルウェアを登録するだけ
app.use(koaJwt({ secret: 'KEY' }));
// 2. ctx.state.user ですぐに使える
koa-passport + passport-jwt:アダプターを介した統合
Passport は本来 Express 向けに設計されています。koa-passport が Request/Response オブジェクトを変換して橋渡しを行います。このため、初期化ステップが一つ増えます。
// koa-passport の場合
// 1. 戦略を登録
passport.use('jwt', new JwtStrategy({ ... }, verifyCallback));
// 2. 初期化ミドルウェアを登録
app.use(passport.initialize());
// 3. ルートごとに authenticate を呼ぶ
router.get('/', passport.authenticate('jwt'), handler);
プロジェクトの規模が大きくなると、認証フローの細かい制御が必要になることがあります。ここでは、エラーハンドリングやトークン抽出のカスタマイズ性を比較します。
トークン抽出のカスタマイズ
デフォルトでは Authorization: Bearer <token> ヘッダーからトークンを取得しますが、クエリパラメータや Cookie から取得したい場合があります。
jsonwebtoken
完全に手動です。どこからトークンを取得するかは開発者が自由に実装します。
// 手動で Cookie から取得
const token = ctx.cookies.get('access_token');
const user = jwt.verify(token, 'SECRET');
koa-jwt
getToken オプションでカスタマイズ可能です。
app.use(koaJwt({
secret: 'SECRET',
getToken: (ctx) => ctx.cookies.get('access_token')
}));
passport-jwt
jwtFromRequest で抽出関数を指定します。 extractor の種類が豊富です。
new JwtStrategy({
jwtFromRequest: ExtractJwt.fromExtractors([
ExtractJwt.fromAuthHeaderAsBearerToken(),
(req) => req.cookies?.access_token // カスタム抽出
]),
secretOrKey: 'SECRET'
}, verifyCallback);
エラーハンドリング
認証失敗時の挙動も重要です。デフォルトでは 401 エラーを返しますが、独自のレスポンスを返したい場合があります。
koa-jwt
unless オプションで除外パスを設定できますが、エラーハンドリングはミドルウェアチェーンで捕捉します。
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
if (err.status === 401) {
ctx.status = 401;
ctx.body = { message: 'カスタムエラーメッセージ' };
}
}
});
koa-passport
authenticate オプションでコールバックを渡すことで、失敗時の処理をルーティングレベルで制御できます。
router.get('/protected', passport.authenticate('jwt', { session: false }, (err, user) => {
if (!user) {
ctx.status = 401;
ctx.body = { message: 'カスタムエラーメッセージ' };
return;
}
ctx.state.user = user;
}));
将来的に JWT 以外の認証(Google、GitHub、ローカル認証など)を追加する予定があるかどうかが、選定の決定的な要因になります。
jsonwebtoken / koa-jwt
JWT 専用です。他の認証方式を追加するには、別途ミドルウェアを実装するか、別のライブラリを導入する必要があります。エコシステムは単一目的に特化しています。
passport-jwt / koa-passport
Passport.js エコシステムの一部です。passport-local(ID/ パスワード)や passport-google-oauth などを同じ設定で追加できます。認証戦略が統一されるため、大規模なアプリケーションで管理コストが下がります。
// Passport エコシステムなら複数の戦略を併用可能
passport.use(new LocalStrategy(...));
passport.use(new GoogleStrategy(...));
passport.use(new JwtStrategy(...));
// すべて koa-passport で統一的に扱える
router.post('/login', passport.authenticate('local'));
router.get('/oauth', passport.authenticate('google'));
router.get('/api', passport.authenticate('jwt'));
| 機能 | jsonwebtoken | koa-jwt | passport-jwt + koa-passport |
|---|---|---|---|
| 抽象化レベル | 低(ユーティリティ) | 中(ミドルウェア) | 高(フレームワーク + 戦略) |
| フレームワーク | 非依存 | Koa 専用 | Koa (Passport アダプター経由) |
| 設定の手間 | 手動実装が必要 | 最小限 | 初期化と戦略定義が必要 |
| 拡張性 | 低い(JWT のみ) | 低い(JWT のみ) | 高い(多様な戦略と併用可能) |
| エラー制御 | 完全手動 | ミドルウェアチェーン | コールバックで細かく制御 |
| 推奨ユースケース | カスタム実装、学習用 | シンプルな Koa API | 複雑な認証要件、複数戦略 |
プロジェクトの要件に応じて、以下のように選択するのが賢明です。
1. シンプルな Koa API サーバーの場合
koa-jwt を選択してください。設定が簡単で、Koa の哲学に合致しています。JWT 認証だけで完結するプロジェクトでは、Over-Engineering(過剰設計)を避けることができます。
2. 複数の認証方式を扱う場合
passport-jwt と koa-passport の組み合わせを選択してください。将来的に OAuth や ID/ パスワード認証を追加する可能性があるなら、最初から Passport エコシステムに載せておくことで、後々のリファクタリングコストを削減できます。
3. 完全な制御が必要な場合
jsonwebtoken を直接使用してください。ミドルウェアの挙動に不満がある場合や、独自の認証プロトコルを構築する場合には、このライブラリが最も柔軟です。ただし、セキュリティ実装の責任はすべて開発者にあります。
結論として、多くの現代的な Koa プロジェクトでは、koa-jwt がバランスの取れた選択です。しかし、エンタープライズレベルの認証要件がある場合は、Passport エコシステムへの投資が長期的なメンテナンス性を高めます — どちらを選ぶにせよ、jsonwebtoken がその根幹にあることを理解しておくことが重要です。
カスタムミドルウェアを作成したい場合や、フレームワークに依存しない純粋な JWT 操作が必要な場合は jsonwebtoken を選択します。認証フローの每一个细节を制御したい上級者向けです。
Passport.js のエコシステムを利用する場合、特に JWT 以外の認証戦略(Google ログインなど)と組み合わせたい場合は passport-jwt を選択します。単体ではミドルウェアとして動作しないため、アダプターと併用が必要です。
Koa を使用しつつ、Passport の豊富な戦略(passport-jwt など)を利用したい場合に必須です。Passport の初期化とルーティングを Koa 向けに変換する役割を果たします。
Koa を使用していて、JWT 認証のみが必要で、追加の認証戦略(OAuth など)を予定していない場合は koa-jwt が最適です。設定がシンプルで、Koa のコンテキストに自然に統合されます。
| Build | Dependency |
|---|---|
An implementation of JSON Web Tokens.
This was developed against draft-ietf-oauth-json-web-token-08. It makes use of node-jws
$ npm install jsonwebtoken
(Asynchronous) If a callback is supplied, the callback is called with the err or the JWT.
(Synchronous) Returns the JsonWebToken as string
payload could be an object literal, buffer or string representing valid JSON.
Please note that
expor any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity.
If
payloadis not a buffer or a string, it will be coerced into a string usingJSON.stringify.
secretOrPrivateKey is a string (utf-8 encoded), buffer, object, or KeyObject containing either the secret for HMAC algorithms or the PEM
encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { key, passphrase } can be used (based on crypto documentation), in this case be sure you pass the algorithm option.
When signing with RSA algorithms the minimum modulus length is 2048 except when the allowInsecureKeySizes option is set to true. Private keys below this size will be rejected with an error.
options:
algorithm (default: HS256)expiresIn: expressed in seconds or a string describing a time span vercel/ms.
Eg:
60,"2 days","10h","7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120"is equal to"120ms").
notBefore: expressed in seconds or a string describing a time span vercel/ms.
Eg:
60,"2 days","10h","7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120"is equal to"120ms").
audienceissuerjwtidsubjectnoTimestampheaderkeyidmutatePayload: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.allowInsecureKeySizes: if true allows private keys with a modulus below 2048 to be used for RSAallowInvalidAsymmetricKeyTypes: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided.There are no default values for
expiresIn,notBefore,audience,subject,issuer. These claims can also be provided in the payload directly withexp,nbf,aud,subandissrespectively, but you can't include in both places.
Remember that exp, nbf and iat are NumericDate, see related Token Expiration (exp claim)
The header can be customized via the options.header object.
Generated jwts will include an iat (issued at) claim by default unless noTimestamp is specified. If iat is inserted in the payload, it will be used instead of the real timestamp for calculating other things like exp given a timespan in options.expiresIn.
Synchronous Sign with default (HMAC SHA256)
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
Synchronous Sign with RSA SHA256
// sign with RSA SHA256
var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' });
Sign asynchronously
jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) {
console.log(token);
});
Backdate a jwt 30 seconds
var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh');
The standard for JWT defines an exp claim for expiration. The expiration is represented as a NumericDate:
A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.
This means that the exp field should contain the number of seconds since the epoch.
Signing a token with 1 hour of expiration:
jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60),
data: 'foobar'
}, 'secret');
Another way to generate a token like this with this library is:
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 });
//or even better:
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: '1h' });
(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error.
(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.
Warning: When the token comes from an untrusted source (e.g. user input or external requests), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected
token is the JsonWebToken string
secretOrPublicKey is a string (utf-8 encoded), buffer, or KeyObject containing either the secret for HMAC algorithms, or the PEM
encoded public key for RSA and ECDSA.
If jwt.verify is called asynchronous, secretOrPublicKey can be a function that should fetch the secret or public key. See below for a detailed example
As mentioned in this comment, there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass Buffer.from(secret, 'base64'), by doing this the secret will be decoded using base64 and the token verification will use the original random bytes.
options
algorithms: List of strings with the names of the allowed algorithms. For instance, ["HS256", "HS384"].
If not specified a defaults will be used based on the type of key provided
- secret - ['HS256', 'HS384', 'HS512']
- rsa - ['RS256', 'RS384', 'RS512']
- ec - ['ES256', 'ES384', 'ES512']
- default - ['RS256', 'RS384', 'RS512']
audience: if you want to check audience (aud), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions.
Eg:
"urn:foo",/urn:f[o]{2}/,[/urn:f[o]{2}/, "urn:bar"]
complete: return an object with the decoded { payload, header, signature } instead of only the usual content of the payload.issuer (optional): string or array of strings of valid values for the iss field.jwtid (optional): if you want to check JWT ID (jti), provide a string value here.ignoreExpiration: if true do not validate the expiration of the token.ignoreNotBefore...subject: if you want to check subject (sub), provide a value hereclockTolerance: number of seconds to tolerate when checking the nbf and exp claims, to deal with small clock differences among different serversmaxAge: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span vercel/ms.
Eg:
1000,"2 days","10h","7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120"is equal to"120ms").
clockTimestamp: the time in seconds that should be used as the current time for all necessary comparisons.nonce: if you want to check nonce claim, provide a string value here. It is used on Open ID for the ID Tokens. (Open ID implementation notes)allowInvalidAsymmetricKeyTypes: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided.// verify a token symmetric - synchronous
var decoded = jwt.verify(token, 'shhhhh');
console.log(decoded.foo) // bar
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo) // bar
});
// invalid token - synchronous
try {
var decoded = jwt.verify(token, 'wrong-secret');
} catch(err) {
// err
}
// invalid token
jwt.verify(token, 'wrong-secret', function(err, decoded) {
// err
// decoded undefined
});
// verify a token asymmetric
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, function(err, decoded) {
console.log(decoded.foo) // bar
});
// verify audience
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
// if audience mismatch, err == invalid audience
});
// verify issuer
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
// if issuer mismatch, err == invalid issuer
});
// verify jwt id
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) {
// if jwt id mismatch, err == invalid jwt id
});
// verify subject
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) {
// if subject mismatch, err == invalid subject
});
// alg mismatch
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) {
// if token alg != RS256, err == invalid signature
});
// Verify using getKey callback
// Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys.
var jwksClient = require('jwks-rsa');
var client = jwksClient({
jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json'
});
function getKey(header, callback){
client.getSigningKey(header.kid, function(err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
jwt.verify(token, getKey, options, function(err, decoded) {
console.log(decoded.foo) // bar
});
(Synchronous) Returns the decoded payload without verifying if the signature is valid.
Warning: This will not verify whether the signature is valid. You should not use this for untrusted messages. You most likely want to use
jwt.verifyinstead.
Warning: When the token comes from an untrusted source (e.g. user input or external request), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected
token is the JsonWebToken string
options:
json: force JSON.parse on the payload even if the header doesn't contain "typ":"JWT".complete: return an object with the decoded payload and header.Example
// get the decoded payload ignoring signature, no secretOrPrivateKey needed
var decoded = jwt.decode(token);
// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload)
Possible thrown errors during verification. Error is the first argument of the verification callback.
Thrown error if the token is expired.
Error object:
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'TokenExpiredError',
message: 'jwt expired',
expiredAt: 1408621000
}
*/
}
});
Error object:
.)jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'JsonWebTokenError',
message: 'jwt malformed'
}
*/
}
});
Thrown if current time is before the nbf claim.
Error object:
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'NotBeforeError',
message: 'jwt not active',
date: 2018-10-04T16:10:44.000Z
}
*/
}
});
Array of supported algorithms. The following algorithms are currently supported.
| alg Parameter Value | Digital Signature or MAC Algorithm |
|---|---|
| HS256 | HMAC using SHA-256 hash algorithm |
| HS384 | HMAC using SHA-384 hash algorithm |
| HS512 | HMAC using SHA-512 hash algorithm |
| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm |
| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm |
| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm |
| PS256 | RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| PS384 | RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| PS512 | RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0) |
| ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm |
| ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm |
| ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm |
| none | No digital signature or MAC value included |
First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system.
We are not comfortable including this as part of the library, however, you can take a look at this example to show how this could be accomplished. Apart from that example there are an issue and a pull request to get more knowledge about this topic.
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
This project is licensed under the MIT license. See the LICENSE file for more info.