
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
express-jsonwebtoken
Advanced tools
JsonWebToken (JWT) manager for express,
This module managing the authentication using JSON Web Tokens for express application. and allow you to encrypt the tokens and blacklist sign out tokens,
this module also has middleware for authenticate and sign out
$ npm install express-jsonwebtoken
Before you can use this package in your app, you must initial it by this code: (the jwt.secret property is required for using this package)
var jwtExpress = require('express-jsonwebtoken');
var jwtManager = new JwtExpress({
jwt: {
secret: 'mySecretShouldNeverBeTold',
}
});
jwtExpress.sign(payload, [options = {}, callback = null])
Sign your payload with the initiated options for jwt.options.
payload: data you want to sign with jwt algorithm
options: override the initiated options to sign with.Must be type of object.
callback: should use callback function instead of return sync value of the sign method.
callback sign: function(Error|null,null|String)
jwtExpress.verify(token, [options = {}, callback = null, onlyPayload = true]) {
verify the token and return the payload value, using jwt.options as default options
token: token to be verified and get payload from
options: override the initiated options to sign with.Must be type of object.
callback: should use callback function instead of return sync value of the sign method.
callback sign: function(Error|null,null|String)
onlyPayload: indicate if return the payload data only or the whole token data
WARNING: this method not validate the token before exclude the payload and open possebility for injections
jwtExpress.decode(token, [options = {}, callback = null, onlyPayload = true]) {
verify the token and return the payload value, using jwt.refresh.options as default options
token: token to be verified and get payload from
options: override the initiated options to sign with.Must be type of object.
callback: should use callback function instead of return sync value of the sign method.
callback sign: function(Error|null,null|String)
onlyPayload: indicate if return the payload data only or the whole token data
jwtExpress.signRefresh(payload, [options = {}, callback = null])
Sign your payload with the initiated options for jwt.refresh.options.
payload: data you want to sign with jwt algorithm
options: override the initiated options to sign with.Must be type of object.
callback: should use callback function instead of return sync value of the sign method.
callback sign: function(Error|null,null|String)
jwtExpress.verifyRefresh(token, [options = {}, callback = null, onlyPayload = true]) {
verify the token and return the payload value, using jwt.refresh.options as default options
token: token to be verified and get payload from
options: override the initiated options to sign with.Must be type of object.
callback: should use callback function instead of return sync value of the sign method.
callback sign: function(Error|null,null|String)
onlyPayload: indicate if return the payload data only or the whole token data
middleware for authenticate users by jwt token.
If the token is valid, req.user (or any other property that preset on init method) will be set with the token payload data
example:
var jwtExpress = require('express-jsonwebtoken');
var jwtManager = new JwtExpress({
jwt: {
secret: 'mySecretShouldNeverBeTold',
middleware:{
tokenPayloadKey: 'user'
}
}
});
...
app.get('/admin',
jwtManager.middleware({
// any option override available
}),
function(req, res) {
// your logic goes here
// example
if (!req.user.isAdmin) {
return res.sendStatus(401);
}
res.sendStatus(200);
});
middleware for sign out user that add to blacklist the user token.
for really make this work, you must enable blacklist on init, jwt:{useBlacklist = true}
example:
var jwtExpress = require('express-jsonwebtoken');
var jwtManager = new JwtExpress({
jwt: {
secret: 'mySecretShouldNeverBeTold',
useBlacklist: true
}
});
...
app.get('/sign-out',
jwtExpress.middlewareSignOut({
// any option override available
}),
function(req, res) {
res.sendStatus(200);
});
middleware for refreshing jwt token (for using default refresh middleware, you must sign & refreshSign with the exact same payload)
example:
var jwtExpress = require('express-jsonwebtoken');
var jwtManager = new JwtExpress({
jwt: {
secret: 'mySecretShouldNeverBeTold',
useBlacklist: true
}
});
...
app.get('/sign-out',
jwtManager.middlewareSignOut({
// any jwt option override available
}, {
// any refresh options override avaible
}),
function(req, res) {
res.sendStatus(200);
});
The only required param is jwt.secret value
new JwtExpress({
jwt: {
options: {
algorithm: 'HS256',
expiresIn: '5m',
// notBefore: undefined,
// audience: undefined,
// issuer: undefined,
// jwtid: undefined,
// subject: undefined,
// noTimestamp: undefined,
// header: undefined,
// keyid: undefined,
// mutatePayload: false
},
refresh: {
options: {
algorithm: 'HS256',
expiresIn: '7d',
// notBefore: undefined,
// audience: undefined,
// issuer: undefined,
// jwtid: undefined,
// subject: undefined,
// noTimestamp: undefined,
// header: undefined,
// keyid: undefined,
// mutatePayload: false
},
getToken: (req) => {
const refreshToken = req.header('refresh-token');
if (refreshToken && typeof refreshToken === "string") {
const parts = refreshToken.split(' ');
if (parts.length === 2) {
const scheme = parts[0];
const token = parts[1];
if (scheme === "Bearer") {
return token;
} else {
throw new JwtExpressError(JwtExpressError.ErrorCodes.INVALID_TOKEN_SCHEMA);
}
} else {
throw new JwtExpressError(JwtExpressError.ErrorCodes.INVALID_TOKEN);
}
} else if (req.query.token) {
return req.query.token
} else {
throw new JwtExpressError(JwtExpressError.ErrorCodes.MISSING_TOKEN);
}
},
},
secret: null,
useEncrypt: false,
useBlacklist: false,
getToken: (req) => {
const authorizationHeader = req.header('authorization')
if (authorizationHeader && typeof authorizationHeader === "string") {
const parts = authorizationHeader.split(' ');
if (parts.length === 2) {
const scheme = parts[0];
const token = parts[1];
if (scheme === "Bearer") {
return token;
} else {
throw new JwtExpressError(JwtExpressError.ErrorCodes.INVALID_TOKEN_SCHEMA);
}
} else {
throw new JwtExpressError(JwtExpressError.ErrorCodes.INVALID_TOKEN);
}
} else if (req.query.token) {
return req.query.token;
} else {
throw new JwtExpressError(JwtExpressError.ErrorCodes.MISSING_TOKEN);
}
},
middleware: {
tokenPayloadKey: 'user',
},
blacklist: {
driverName: 'memory',
driverParams: {
clearExpiredItemsInterval: '5m',
clearExpiredItemsIntervalDelay: null,
},
},
},
encryption: {
algorithm: 'aes-256-cbc',
},
localization: {
responses: {
UNKNOWN_ERROR: {
httpCode: 500,
message: 'Unknown error, please try again later.',
},
MISSING_TOKEN: {
httpCode: 400,
message: 'Missing token param.',
},
INVALID_TOKEN_SCHEMA: {
httpCode: 400,
message: 'Token schema is not allowed.',
},
INVALID_TOKEN: {
httpCode: 401,
message: 'Invalid token.',
},
CORRUPTED_TOKEN: {
httpCode: 400,
message: 'Corrupted token.',
},
TOKEN_BLACKLISTED: {
httpCode: 401,
message: 'Token in blacklist.',
},
TOKEN_EXPIRED: {
httpCode: 401,
message: 'Token in expired.',
},
JWT_MALFORMED: {
httpCode: 400,
message: 'Jwt token malformed.',
},
JWT_SIGNATURE_IS_REQUIRED: {
httpCode: 400,
message: 'Jwt signature is required.',
},
INVALID_SIGNATURE: {
httpCode: 400,
message: 'Invalid signature.',
},
JWT_AUDIENCE_INVALID: {
httpCode: 400,
message: 'Jwt audience invalid. expected: ${expected}',
},
JWT_ISSUER_INVALID: {
httpCode: 400,
message: 'Jwt issuer invalid. expected: ${expected}.',
},
JWT_ID_INVALID: {
httpCode: 400,
message: 'Jwt id invalid. expected: ${expected}',
},
JWT_SUBJECT_INVALID: {
httpCode: 400,
message: 'Jwt subject invalid. expected ${expected}',
},
},
},
});
=======
Eg:
'HS256','HS384','HS512','RS256', 'RS512'
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").
Eg:
'HS256','HS384','HS512','RS256', 'RS512'
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").
Eg:
req[key]= parsed token`
Eg:
req.user
Note: Other than memory will coming soon
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").
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").
Note: Other than aes-256-cbc will coming soon
Note: Must be Object with all keys as the file
module.exports = {
UNKNOWN_ERROR: {
httpCode: 500,
message: 'Unknown error, please try again later.',
},
MISSING_TOKEN: {
httpCode: 400,
message: 'Missing token param.',
},
INVALID_TOKEN_SCHEMA: {
httpCode: 400,
message: 'Token schema is not allowed.',
},
INVALID_TOKEN: {
httpCode: 401,
message: 'Invalid token.',
},
CORRUPTED_TOKEN: {
httpCode: 400,
message: 'Corrupted token.',
},
TOKEN_BLACKLISTED: {
httpCode: 401,
message: 'Token in blacklist.',
},
TOKEN_EXPIRED: {
httpCode: 401,
message: 'Token in expired.',
},
JWT_MALFORMED: {
httpCode: 400,
message: 'Jwt token malformed.',
},
JWT_SIGNATURE_IS_REQUIRED: {
httpCode: 400,
message: 'Jwt signature is required.',
},
INVALID_SIGNATURE: {
httpCode: 400,
message: 'Invalid signature.',
},
JWT_AUDIENCE_INVALID: {
httpCode: 400,
message: 'Jwt audience invalid. expected: ${expected}',
},
JWT_ISSUER_INVALID: {
httpCode: 400,
message: 'Jwt issuer invalid. expected: ${expected}.',
},
JWT_ID_INVALID: {
httpCode: 400,
message: 'Jwt id invalid. expected: ${expected}',
},
JWT_SUBJECT_INVALID: {
httpCode: 400,
message: 'Jwt subject invalid. expected ${expected}',
},
};
Ran, Nofar, Yogev, Yaron
This project is licensed under the MIT license. See the LICENSE file for more info.
FAQs
JsonWebToken (JWT) manager for express,
We found that express-jsonwebtoken demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.