代码之家  ›  专栏  ›  技术社区  ›  markovchain

将ObjectID与jwt一起使用。签名()和验证()

  •  2
  • markovchain  · 技术社区  · 7 年前

    登录到我的系统后,我运行MongoDB _id 通过 jsonwebtoken sign

    我现在想解码会话并恢复字符串 _id verify 方法我这样做不是为了身份验证(这已经通过在DB中查找会话来处理了)。我正在恢复 因此,我可以在单独的集合中记录用户的活动。我运行 验证 req.decoded

    但是,当我登录时 ,它是BSON对象,而不是字符串:

    { _bsontype: 'ObjectID',
      id:
       { type: 'Buffer',
         data: [ 89, 128, 145, 134, 118, 9, 216, 20, 175, 174, 247, 33 ] },
      iat: 1501903389,
      exp: 1501989789 }
    

    _id 值,以便我可以在我的集合中再次查找此记录?

    我试过的

    • model.find(req.decoded).then() 给我这个错误:

    • model.find({_id: req.decoded}) 给我这个错误:

      {CastError:model[model here]的路径“\u id”处的值[contents of req.decoded here]的转换为ObjectId失败

    • req.decoded.toString()

    • JSON.stringify(req.decoded) 将BSON转换为字符串

    1 回复  |  直到 7 年前
        1
  •  2
  •   Neil Lunn    7 年前

    当然,这取决于您实际提供数据的方式 .sign() 首先,简单地提供 ObjectID 而是提供值。

    general usage for .sign()

    如果负载不是缓冲区或字符串,则将使用JSON.stringify将其强制为字符串。

    简而言之,该版本将“字符串化”对象形式,需要一些“挖掘”。在您的形式中,解码对象具有以下属性: id 子属性为 data 其中包含可转换为 Buffer .这就是你要做的:

      let newId = Buffer.from(req.decoded.id.data).toString('hex');
    

    newId 'hex' ObjectId _id .

    .符号() .toString() 来自 ObjectId .verify() 是否只是提供的“十六进制字符串”,而不是 JSON.stringify 上的结果 ObjectID 它本身

    用列表演示:

    const bson = require('bson'),
          jwt = require('jsonwebtoken');
    
    // Stored ObjectID
    console.log("Round 1");
    (function() {
      let id = new bson.ObjectID();
      console.log("Created: %s", id);
    
      let token = jwt.sign(id,'shhh');                // Supply value as ObjectID
      let decoded = jwt.verify(token,'shhh');
    
      console.log("Interim");
      console.log(decoded);
    
      let newId = Buffer.from(decoded.id.data).toString('hex');
      console.log("Decoded: %s", newId);
    })();
    
    console.log("\nRound 2");
    // Stored String value
    (function() {
    
      let id = new bson.ObjectID();
      console.log("Created: %s", id);
    
      let token = jwt.sign(id.toString(), 'shhh');    // Supply value as string
      let decoded = jwt.verify(token,'shhh');
    
      console.log("Decoded: %s", decoded);
    
    })();
    

    给出输出,显示输入值和解码值:

    Round 1
    Created: 59857328090c497ce787d087
    Interim
    { _bsontype: 'ObjectID',
      id:
       { type: 'Buffer',
         data: [ 89, 133, 115, 40, 9, 12, 73, 124, 231, 135, 208, 135 ] },
      iat: 1501917992 }
    Decoded: 59857328090c497ce787d087
    
    Round 2
    Created: 59857328090c497ce787d088
    Decoded: 59857328090c497ce787d088
    

    .符号() .验证()