【问题标题】:Integrating json web token in oauth20在 oauth20 中集成 json Web 令牌
【发布时间】: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


    【解决方案1】:

    我找到了解决方案,您需要在passport.serializeUser 中传递标记,然后通过重定向发送它以响应重定向 url。

    序列化用户函数:

    passport.serializeUser(async (user, cb) => {
      const payload = {
        user: {
          id: user.id
        }
      };
      token = jwtToken.sign(payload, config.get("jwtSecret"), {
        expiresIn: 360000
      });
      console.log("serialize");
      cb(null, user.id);
    });
    

    重定向路由:

    router.get(
      "/google/redirect",
      passport.authenticate("google", { sessionStorage: false }),
      (req, res) => {
        res.redirect("/" + token);
      }
    );
    

    【讨论】:

      猜你喜欢
      • 2015-07-20
      • 2018-06-11
      • 2018-02-02
      • 2016-08-01
      • 2016-03-14
      • 2015-06-03
      • 1970-01-01
      • 2017-04-16
      • 2015-05-23
      相关资源
      最近更新 更多