Search code examples
javascriptnode.jsjwtdecodefeathersjs

How to decode jwt and get from this userId in feathersjs?


I'm using Feathers framework to my nodejs application and i have done creation of jwt in following way

  app.service('authentication').hooks({
    before: {
      create: [
        authentication.hooks.authenticate(config.strategies),
        function (hook) {
         hook.params.payload = {
            userId: hook.params.user.userId,
            accountId: hook.params.user.accountId
          };
          return Promise.resolve(hook);
        }
      ],
      remove: [
        authentication.hooks.authenticate('jwt')
      ]
    }
  });

now i have doubt how to get userId from token using jwt decoded data.


Solution

  • using jwt-decode lib will provide the jwt decode functionality in feathersjs

    const decode = require('jwt-decode');
    
    hook.params.headers.authorization =  'eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyIsInR5cGUiOiJhY2Nlc3MifQ.eyJ1c2VySWQiOjEsImFjY291bnRJZCI6MSwiaWF0IjoxNTA2MzMwNzIyLCJleHAiOjE1MDY0MTcxMjIsImF1ZCI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20iLCJpc3MiOiJmZWF0aGVycyIsInN1YiI6ImFub255bW91cyJ9.gZrDJhmzdpt9-7OCeRcKiayQiKbtv-3UaTkN1BhOCAI'
    
    var userId =  decode(hook.params.headers.authorization).userId; 
    console.log(userId)
    1