简体   繁体   English

jsonwebtoken: expiresIn 不会过期?

[英]jsonwebtoken: expiresIn does not expires?

I am trying to set the token to be expired in one hour following the example from the guide :我正在尝试按照指南中的示例将令牌设置为在一小时内过期:

jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 })

But the toke never expires in a few hours later:但是令牌永远不会在几个小时后过期:

curl -XGET -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTU4OTAzMDI3LCJleHAiOjE1NTg5MDY2Mjd9.8uHKDM4Hgy08kw_0CLib2QnzqudeC_RsIlh8e9uURT0' 'http://localhost:3000/api/users'

Have I missing something?我错过了什么吗?

How do I set it to expire in 1 or 5 minutes?如何将其设置为在 1 或 5 分钟后过期?

The code for verifying the token:验证令牌的代码:

import jwt from 'jsonwebtoken'
import config from '../config'

export default async (ctx, next) => {
  try {
    await next()

    if(ctx.req.hasOwnProperty('headers') && ctx.req.headers.hasOwnProperty('authorization')) {
      ctx.req.user = jwt.verify(ctx.req.headers['authorization'], config.JWT_SECRET, function (err, payload) {
        console.log(payload)
      })
    } else {
      // If there is no autorization header, return 401 status code.
      ctx.throw(401, 'Protected resource, use Authorization header to get access')
    }
  } catch (err) {
    ctx.status = err.status || 500

    ctx.type = 'json'
    ctx.body = {
      status: ctx.status,
      message: err.message
    }

    ctx.app.emit('error', err, ctx)
  }
}

From the docs it says that文档中它说

This means that the exp field should contain the number of seconds since the epoch.这意味着 exp 字段应该包含自纪元以来的秒数

So:所以:

  • 1 minute => 60 1 分钟 => 60
  • 5 minutes => 60 * 5 5 分钟 => 60 * 5

Which gives这使

// Expires in 5 minutes
jwt.sign({
  data: 'foobar'
}, 'secret', { expiresIn: 5 * 60 })

The jwt.verify function in the question code sample is using a callback function to return it's asynchronous result.问题代码示例中的jwt.verify函数使用回调函数返回它的异步结果。

Koa is promise based and won't pick up this callback result or catch any errors being raised (including a TokenExpiredError ). Koa 是基于 Promise 的,不会获取此回调结果或捕获任何引发的错误(包括TokenExpiredError )。 The verify err is completely ignored at the moment.验证err目前完全被忽略。

jwt.verify can be converted into a promise, or if you don't supply the callback argument the function will return synchronously. jwt.verify可以转换为一个promise,或者如果你不提供回调参数,函数将同步返回。 The try / catch will then work as expected.然后try / catch将按预期工作。

import util from 'util'
import jwt from 'jsonwebtoken'
import config from '../config'

export const verifyPromise = util.promisify(jwt.verify)

export default async function verifyToken(ctx, next){

  if(!ctx.req.hasOwnProperty('headers') || !ctx.req.headers.hasOwnProperty('authorization')) {
    return ctx.throw(401, 'Protected resource, use Authorization header to get access')
  }

  try {
    let payload = await verifyPromise(ctx.req.headers['authorization'], config.JWT_SECRET, {})
    console.log(payload)
  }
  catch (err) {
    if (err.name === 'TokenExpiredError'){
      return ctx.throw(401, 'Protected resource, token expired')
    }

    console.error(err)
    return ctx.throw(500, 'Protected resource, token error')

  }

  await next()

}

The jwt.sign function takes a number as seconds or a string description of time from zeit/ms jwt.sign函数将数字作为秒或从zeit/ms获取时间的字符串描述

{ expiresIn: 1 * 60 }
{ expiresIn: '1m' }

看起来您的代码假定属性的过期和发布定义为毫秒(60000 毫秒 = 60 秒 = 1 分钟)。

  var token = jwt.sign({ id: user.id }, config.secret,{ expiresIn: 60});

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

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