【问题标题】:How to decode jwt and get from this userId in feathersjs?如何解码jwt并从feathersjs中的这个userId获取?
【发布时间】:2017-09-28 00:56:36
【问题描述】:

我在我的 nodejs 应用程序中使用 Feathers 框架,并且我已经按照以下方式创建了 jwt

  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')
      ]
    }
  });

现在我怀疑如何使用 jwt 解码数据从令牌中获取 userId。

【问题讨论】:

    标签: javascript node.js jwt decode feathersjs


    【解决方案1】:

    使用 jwt-decode 库将在 feathersjs 中提供 jwt 解码功能

    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
    

    【讨论】:

    • 我能知道在 src/authentication.js 中的哪里做这个
    • 在Feathers新版jwt对象结构发生变化,userId改为sub var userId = decode(hook.params.headers.authorization).sub
    猜你喜欢
    • 2019-12-12
    • 2023-01-23
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2020-09-27
    • 2020-04-22
    • 2016-01-07
    相关资源
    最近更新 更多