【问题标题】:Combining a passport openID-stategy with JWT将护照 openID-stategy 与 JWT 相结合
【发布时间】:2015-12-26 23:17:27
【问题描述】:

我在尝试使用 openID (passport-steam) 对 passport.js 进行身份验证时遇到问题,然后使用令牌 (JWT) 而不是会话。

我当前的代码如下所示:

app.post('/auth/steam', passport.authenticate('steam'));

app.get('/auth/steam/return',
  passport.authenticate('steam', { failureRedirect: '/', session: false }),
  function(req, res) {
    var token = jwt.encode({ useridentifier: req.user.identifier}, tokenSecret);

    res.redirect('/');
  });

但是,我遇到的问题是:我应该如何将令牌传回给客户端?由于是从 Steam 站点返回后运行的 GET 请求,我无法简单回复

res.json(token)

就像我看到人们使用本地策略和智威汤逊一样。

我设法想出的唯一解决方案是使用包含令牌的会话(例如 connect-flash),并在客户端被重定向到“/”后通过 REST API 将其传达给客户端,但重点使用 JWT 是为了避免使用会话,不是吗?

【问题讨论】:

    标签: node.js authentication express passport.js jwt


    【解决方案1】:

    经过多天的思考却无处可去,我设法找到了另一种解决方法,即使用 cookie。

    我发现了护照提供的自定义回调,我可以在其中设置响应的标头,所以我在重定向之前设置了一个这样的:

    res.cookie('token', token, { httpOnly: true }); 
    

    (还不安全,因为我只是在本地服务器上测试)

    这就是整个代码现在的样子:

    app.get('/auth/steam', passport.authenticate('steam'));
    
    app.get('/auth/steam/return', 
      function(req, res, next) {
        passport.authenticate('steam', function(err, user, info){ 
          var payload = {
            user: user.identifier
          };
    
          var token = jwt.sign(payload, "thisisnotthesecretiactuallyuse", {expiresIn : 60*60*24});
          res.cookie('token', token, { httpOnly: true /* TODO: Set secure: true */ }); 
    
          res.redirect('/'); 
        })(req, res, next)
      });
    

    【讨论】:

      猜你喜欢
      • 2016-09-25
      • 2019-06-23
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2018-01-13
      • 2020-03-08
      相关资源
      最近更新 更多