将非用户字段添加到有效负载以在JWT令牌中使用

时间:2016-09-29 19:38:19

标签: javascript node.js jwt feathersjs feathers-authentication

您好我希望在身份验证过程中向有效负载添加非用户字段,以便我可以包含在JWT令牌中。

请求是这样的:

{ "scriptId": "script1", "password": "password", "userName": "user1" }

config就像这样:

  "auth": {
    "local": {
      "usernameField" : "scriptId"
    },
    "token": {
      "secret": "mysecret",
      "payload": ["scriptId","userName"],
      "expiresIn": "10min"
    },
    "successRedirect": "/chat.html"
  }

如何传递userName参数,以便我可以在auth / token服务的before钩子中检索它,这样我就可以将它传递给hook.data

或者,如果有更好的方法,请告诉我。

3 个答案:

答案 0 :(得分:1)

检查this PR:

// default.json
{
  "auth": {
    "extraFields": [
      "email",
      "roles"
    ]
  }
}

extraFields是您的用户对象的字段名。因此,JWT中的数据需要由您的用户端点提供。

答案 1 :(得分:1)

您可以按照以下方式添加

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

答案 2 :(得分:0)

  1. 使用命令' feathers generate hook'

  2. 创建一个名为add_payload(或任何你想要的)的挂钩以进行服务验证
  3. 在/src/service/authentication/index.js里面添加导出结尾

  4. app.service(' / AUTH /本地&#39)之后(hooks.after);

    1. 在/ src / service / authentication / hooks中创建index.js文件,内容应如下所示:
    2. 'use strict' const addPayload = require('./add_payload'); const globalHooks = require('../../../hooks'); const hooks = require('feathers-hooks'); exports.after = { all: [addPayload()], find: [], get: [], create: [], update: [], patch: [], remove: [] };

        钩子函数内的
      1. ... /src/service/authentication/hooks/add_payload.js

        return function(hook) { hook.result.aa = "xyz"; // add whatever you want to the return here... hook.addPayload = true; };