简体   繁体   English

在oauth20中集成json web令牌

[英]Integrating json web token in oauth20

I am trying to create an api where user can sign up with an email or can sign in with google, I use json web token for authentication and oauth20, the problem is, can, I pass a jwt with oauth? 我正在尝试创建一个api用户可以使用电子邮件注册或者可以使用google登录,我使用json web令牌进行身份验证和oauth20,问题是,我可以通过一个带有oauth的jwt吗?

I have tried passing it and, I get a token if, I console log, but how do, I pass it to the user, like can i some way attach it to the req.user object in the cb by oauth or something like that? 我试过传递它,我得到一个令牌,如果,我控制日志,但是怎么做,我把它传递给用户,就像我可以通过某种方式将它附加到cb中的req.user对象oauth或类似的东西?

I am doing this in the google strategy: 我在谷歌策略中这样做:

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

My routes are protected like this: 我的路线受到如下保护:

router.get("/", auth, async (req, res)=>{
...some code
    }

where auth is a middle ware function auth是一个中间件功能

This is the Auth middleware function: 这是Auth中间件功能:

module.exports = function(req, res, next) { 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();

};

I found the solution, you need to pass sign the token in the passport.serializeUser and then send the it with a redirection in response of the redirect url. 我找到了解决方案,你需要在passport.serializeUser传递令牌,然后发送重定向以响应重定向网址。

The serialize user function: 序列化用户功能:

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

The redirection route: 重定向路由:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM