我正在开发一个应用程序,并且希望从一开始就实现安全性,因此我创建了一个私钥/公钥对,并像以下方式设置passport-jwt
(key
是密钥对的公钥部分):
(passport, key) => {
const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: key
};
passport.use(
new JwtStrategy(opts, (payload, done) => {
log.info({message: 'verifying the token', payload});
User.findById(payload.id)
.then(user => {
if (user) {
return done(null, {
id: user._id,
name: user.userName,
email: user.emailAddress
});
}
log.info(payload);
return done(null, false);
})
.catch(err => {
log.error(err)
return done('Unauthorized', false, payload);
});
})
);
};
当用户登录时,我会使用私钥对令牌进行签名,方法如下:
router.post('/login', (req, res) => {
const email = req.body.email;
const password = req.body.password;
User.findOne({ email }).then(user => {
if (!user) {
errors.email = 'No Account Found';
return res.status(404).json(errors);
}
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
const payload = {
id: user._id,
name: user.userName,
email: user.emailAddress
};
log.info(payload);
jwt.sign(payload, private, { expiresIn: 30000000 }, (err, token) => {
if (err)
res.status(500).json({ error: 'Error signing token', raw: err });
// const refresh = uuid.v4();
res.json({ success: true, token: `Bearer ${token}` });
});
} else {
errors.password = 'Password is incorrect';
res.status(400).json(errors);
}
});
});
});
我感觉可能有些东西我没考虑到,但我不确定是什么。
此外,在应用程序初始化时,我也使用以下代码在应用内生成密钥。
const ensureKeys = () => {
return new Promise((resolve, reject) => {
ensureFolder('./keys').then(() => {
/**
* Ensure that both the private and public keys
* are created, and if not create them both.
* Never generate just a single key.
*/
try {
if (
!fs.existsSync('./keys/private.key') &&
!fs.existsSync('./keys/public.key')
) {
log.info('Keys do not exist. Creating them.');
diffHell.generateKeys('base64');
const public = diffHell.getPublicKey('base64');
const private = diffHell.getPrivateKey('base64');
fs.writeFileSync('./keys/public.key', public);
fs.writeFileSync('./keys/private.key', private);
log.info('keys created and being served to the app.');
resolve({ private, public });
} else {
log.info('keys are already generated. Loading from key files.');
const public = fs.readFileSync('./keys/public.key');
const private = fs.readFileSync('./keys/private.key');
log.info('keys loaded from files. Serving to the rest of the app.');
resolve({ private, public });
}
} catch (e) {
log.error('issue loading or generating keys. Sorry.', e);
reject(e);
}
});
});
};