gpt4 book ai didi

node.js - 带有护照 jwt 的非对称 key 。验证总是返回 Unauthorized

转载 作者:行者123 更新时间:2023-12-03 12:13:34 25 4
gpt4 key购买 nike

在应用程序上工作,我从一开始就想要安全,所以我创建了一个私钥/公钥对,我正在设置 passport-jwt像这样:(key 是 key 对的公共(public)部分)

(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);
});
})
);
};

当用户登录时,我使用私钥签署 token ,如下所示:
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);
}
});
});
});

我想我可能缺少一些东西,但我不确定它可能是什么。

此外,我也一直在使用以下代码在初始化时在应用程序内生成 key 。
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);
}
});
});
};

最佳答案

好的,所以问题是双重的。首先,我为护照错误地生成了 key 。根据 passport-jwt 的文档, documentation , key 必须以 PEM 格式编码,并且根据 Medium 上的这篇文章,需要对护照和 JWT 进行更多配置。

最终解决方案包括使用 keypair 在 npm 上可用的库。

以下是用于制作工作结果代码的修改。

const keypair = require('keypair');
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.');
const pair = keypair();
fs.writeFileSync('./keys/public.key', pair.public);
fs.writeFileSync('./keys/private.key', pair.private);
log.info('keys created and being served to the app.');
resolve({ private: pair.private,public: pair.public });
} else {
log.info('keys are already generated. Loading from key files.');
const public = fs.readFileSync('./keys/public.key', 'utf8');
const private = fs.readFileSync('./keys/private.key', 'utf8');
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);
}
});
});
};

key 是用永远不会共享的私钥签名的。
    router.post('/login', (req, res) => {
const { errors, isValid } = require('../validation/user').loginUser(
req.body
);
if (!isValid) {
return res.status(400).json(errors);
}
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,
subject: user.emailAddress,
algorithm: 'RS256'
}, (err, token) => {
if (err)
res.status(500).json({ error: 'Error signing token', raw: err });
res.json({ success: true, token: `Bearer ${token}` });
});
} else {
errors.password = 'Password is incorrect';
res.status(400).json(errors);
}
});
});


以及验证功能:
  const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
secretOrKey: key,
algorithm: ["RS256"]
};
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);
});
})
);

我希望这可以帮助任何希望在 future 使用非对称 key 的人。

关于node.js - 带有护照 jwt 的非对称 key 。验证总是返回 Unauthorized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55012194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com