Run
Run

Reputation: 57196

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?

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)
  }
}

Upvotes: 2

Views: 10968

Answers (3)

Rehan Goraya
Rehan Goraya

Reputation: 131

It looks like your code assumes that the expiration and issued at properties are defined as milliseconds (60000 milliseconds = 60 seconds = 1 minute).

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

Upvotes: 1

Matt
Matt

Reputation: 74690

The jwt.verify function in the question code sample is using a callback function to return it's asynchronous result.

Koa is promise based and won't pick up this callback result or catch any errors being raised (including a TokenExpiredError). The verify err is completely ignored at the moment.

jwt.verify can be converted into a promise, or if you don't supply the callback argument the function will return synchronously. The try/catch will then work as expected.

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

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

Upvotes: 1

molamk
molamk

Reputation: 4116

From the docs it says that

This means that the exp field should contain the number of seconds since the epoch.

So:

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

Which gives

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

Upvotes: 2

Related Questions