5

I was looking at this question on how to set the sub claim of a JWT in FeathersJS, but when I print hook.params, there is no jwt in there. Only authenticated, query, route, provider, headers, user and payload.

So I remain with the question: how can I change the expire time of a JWT token in Feathers?

Sven Deckers
  • 301
  • 1
  • 8

2 Answers2

9

Found it :) I took a look at the code linked in the post (link has changed, but found it back easily when browsing the git repo) and saw that in params, you just need to create your own jwt object and these options will be merged when creating the JWT.

So, if anyone else stumbles upon this, here is my code:

app.service('authentication').hooks({
  before: {
    create: [
      authentication.hooks.authenticate(config.strategies),

      context => {
        context.params.jwt = { expiresIn: 10 }; // 10 seconds
      }
    ],
    remove: [
      authentication.hooks.authenticate('jwt')
    ]
  }
});
Sven Deckers
  • 301
  • 1
  • 8
  • Note that expiration time isn't enforced automatically... in auth v2. https://github.com/feathersjs/feathers/issues/1338 A fake year long JWT would pass the default validation, even if your config has 10m JWT expiration. If someone sees you issuing year long JWT's... you're asking for trouble. Validate the expiration with the algorithm used... a long expiration should use a good algorithm like https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/#JWT-Signing-Algorithms – Ray Foss Mar 06 '21 at 03:27
7

For posterity,

you can easily change that in config/default.json:

{
  // ...
  "authentication": {
    "jwtOptions": {
        "expiresIn": "2 days" // Or "10h" or just a number which is interpreted as seconds
    }
  }
}
Goran.it
  • 5,991
  • 2
  • 23
  • 25
  • 1
    Thank you, this is an easier, yet general approach. The code I posted above can be used when you want to limit session time for a certain user for instance. – Sven Deckers Mar 12 '20 at 10:17