【发布时间】:2019-09-30 08:04:57
【问题描述】:
我正在尝试创建一个 api,用户可以使用电子邮件注册或使用 google 登录,我使用 json Web 令牌进行身份验证和 oauth20,问题是,我可以通过 oauth 传递 jwt 吗?
我已经尝试传递它,并且如果我得到一个令牌,我控制台日志,但是我如何将它传递给用户,就像我可以通过 oauth 以某种方式将它附加到 cb 中的 req.user 对象或类似的东西?
我在谷歌策略中这样做:
async (accessToken, refreshToken, params, profile, cb) => {
const userCheck = await User.findOne({ googleId: profile.id });
if (userCheck) {
const payload = {
user: {
id: userCheck.id
}
};
jwtToken.sign(
payload,
config.get("jwtSecret"),
{ expiresIn: 360000 },
(err, token) => {
if (err) {
throw err;
}
// console.log(token);
return res.json({ token });
},
cb(null, userCheck)
);
我的路线受到这样的保护:
router.get("/", auth, async (req, res)=>{
...some code
}
其中 auth 是一个中间件函数
这是Auth中间件函数:
module.exports = function(req, res, next) {
const token = req.header("x-auth-token");
// If no token found
if (!token)
{
return res.status(401).json({ msg: "User not authorized" });
}
// Set token to user
try {
const decoded = jwtToken.verify(token, config.get("jwtSecret"));
req.user = decoded.user;
}
catch (err)
{
res.
status(401)
.json({ msg: "User not authenticated, please login or sign up" });
}
next();
};
【问题讨论】:
标签: node.js oauth-2.0 jwt gmail-api