【问题标题】:`jsonwebtoken` - `decode` not readable in `Nodejs` api`jsonwebtoken` - 在`Nodejs` api中`decode`不可读
【发布时间】:2016-09-26 22:34:19
【问题描述】:

在我的MEAN 应用程序中,我正在验证用户名和密码。后来我试图让用户信息显示在网页中。但我没有得到可读的数据。

我不知道这里的问题以及我所做的错误。谁能帮帮我。

我的响应 api 是:

apiRoute.get('/me', function(req, res) {
                res.send(req.decoded);
            })

来自req.decoded 我得到的结果是:

{
  "data": {
    "iat": 1474893984,
    "exp": 1474937184
  },
  "status": 200,
  "config": {
    "method": "GET",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "cache": true,
    "url": "/api/me",
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "x-access-token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NzQ4OTM5ODQsImV4cCI6MTQ3NDkzNzE4NH0._Qs2rTaH_oCAZ0c1LOe5oFiUVOZ9jXtpWc0fSykH4Xw"
    }
  },
  "statusText": "OK"
}

在数据中,我没有得到用户名,而是得到一些 num 值。

这是我在用户登录时设置decode 的方式:

apiRoute.use(function( req, res, next ) {

        var token = req.body.token || req.param('token') || req.headers['x-access-token'];

        if( token ) {

            jwt.verify( token, superSecret, function( err, decoded ) {

                if( err ) {

                    return res.status(403).send({
                        success: false,
                        message: 'Failed to authenticate token.'
                    });

                } else {
                    req.decoded = decoded; //setting the value on login.
                    next();

                }

            })

        } else {

            return res.status(403).send({
                success: false,
                message: 'No token provided.'
            });

        }

    })

更新

根据 hpavlino 的建议,我已经更新了我的代码,我在控制台中得到了这个,如果有人找到解决方案,请告诉我:

express deprecated req.param(name): Use req.params, req.body, or req.query instead app\routes\api.js:67:37
token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NzQ5MDAzMDEsImV4cCI6MTQ3NDk4NjcwMX0.8gjrBcX6cD74pix1weqv06qoqw1xFcFHLoR3Mp2fUSE
Access token has expired
GET /api/me 200 19.364 ms - -
GET /app/views/pages/families.html 304 21.319 ms - -
GET /favicon.ico 304 5.999 ms - -

【问题讨论】:

  • 你在分配给req.decode之前检查了decode的值吗?

标签: node.js jwt express-jwt


【解决方案1】:

我使用了这个方法,它解码了正确的信息:

if (token) {
  try {
    var decoded = jwt.decode(token, jwtSecret)
    if (decoded.exp <= Date.now()) {
      console.log("Access token has expired")
      return next()
    }

    console.log(decoded);

  } catch (err) {
    console.log("couldn't decode token: " + err)
    return next()
  }

} else {
  console.log("token not found!")
  return next()
}

【讨论】:

  • 我有令牌控制台,它给出了正确的输出,但是当我控制台解码时它不可读,看起来像上面那样
  • 我收到错误消息:Access token has expired - 那么问题出在哪里?
  • 删除部分"if (decoded.exp
  • 如果在你移除这部分时它可以工作,尝试执行一些其他的过期检查(例如npm package moment)
猜你喜欢
  • 2019-04-30
  • 1970-01-01
  • 2016-10-04
  • 2016-01-21
  • 2017-02-09
  • 2017-03-29
  • 2020-04-24
  • 2018-05-15
相关资源
最近更新 更多