【问题标题】:Node.js. Export a signed cookie to JSON节点.js。将签名的 cookie 导出为 JSON
【发布时间】:2018-05-21 01:11:39
【问题描述】:

我有一个签名的 cookie,可以使用 console.log(req.cookies) 查看它,它的格式如下:

{ 
    'connect.sid':'s:qX4ZrttrjydtrjkgsdghsdghrewynZj4Ew2OUh.tTSILkcvgsegsegsegsr99gmW5
0XLcJefM'
}

既然我知道 cookie,但我也知道秘密,有没有办法将此格式转换为 JSON 格式,其中包含所有字段,例如(名称、值、URL、路径、域、过期、httpOnly、等等……)。

我知道一个名为 EditThisCookie 的 Chrome 插件可以做到这一点。所以我想可以从我的节点应用程序自己做。我只是不知道怎么做。

说明我正在使用 Passport.js 和 OAUTH2 身份验证也很有用。

【问题讨论】:

  • 我想我得到了你想要的,我通过 JWT 签名和验证做到了:npmjs.com/package/jsonwebtoken
  • 谢谢!你用这个方法检索所有字段的值?
  • 您使用 JWT.sign 创建令牌,JWT.verify 在其有效负载中返回对象。
  • 谢谢!我阅读了文档。额外的令牌不会破坏我的 cookie 的完整性吗?在 jwt.sign() 中,我是否将我的 cookie 的值作为有效负载?我提供额外的选择吗?
  • 您能提供一些代码吗?我会投赞成票,并会选择你的答案作为建议的答案

标签: json node.js session cookies


【解决方案1】:

首先,我使用 Passport.JS、Passport-JWT 和 JWT:

$ npm i -s passport passport-jwt jsonwebtoken 

在 app.js 文件中(假设您使用的是 Express.JS) 护照配置

const passport = require('passport');

// TODO in case we cache need to to verify cache first
passport.use(new passportJWT.Strategy({
    'secretOrKey': 'a secret string, longer than this one', // The secret mut be the same all the times
    'jwtFromRequest': passportJWT.ExtractJwt.fromAuthHeaderAsBearerToken()
  }, (payload, done) => {
    // note that if the token is invalid an error will be thrown, else
    // payload will be set as req.user here
    done(null, payload);
}));

app.use(passport.initialize());

然后,在访问受控的路由中使用 passport.authenticate:

app.get('/home', passport.authenticate('jwt', {'session': false}), dashboard);

在您的登录方法中,成功后您将令牌授予用户,您希望将数据保留在有效负载中:

const jwt = require('jsonwebtoken')
// Here you choose the data tha will be on your payload
jwt.sign({'id': user._id, 'username': user.username, 'email': user.email}, 'a secret string, longer than this one');

终于可以通过 req.user int 需要认证的路由访问数据了

【讨论】:

  • 非常感谢我的朋友!但我已经在使用护照-facebook 策略并且我已经有一个 cookie。那么这个方法还能用吗?
猜你喜欢
  • 2018-11-03
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 2017-07-28
  • 1970-01-01
  • 2018-09-01
相关资源
最近更新 更多