如何在Feathersjs身份验证中创建自定义HashPassword功能

问题描述 投票:1回答:3

我在feathersjs文档中注意到了

hashPassword此挂钩用于在将纯文本密码保存到数据库之前对其进行散列。它默认使用bcrypt算法,但可以通过传递自己的options.hash函数进行自定义。

如何在feather js hook,hashPassword hook中应用这个自定义函数?

const { authenticate } = require('@feathersjs/authentication').hooks;

const {
  hashPassword, protect
} = require('@feathersjs/authentication-local').hooks;


module.exports = {
  before: {
    all: [],
    find: [ authenticate('jwt') ],
    get: [ authenticate('jwt') ],
    create: [ hashPassword() ],
    update: [ hashPassword(),  authenticate('jwt') ],
    patch: [ hashPassword(),  authenticate('jwt') ],
    remove: [ authenticate('jwt') ]
  },

  after: {
    all: [ 
      // Make sure the password field is never sent to the client
      // Always must be the last hook
      protect('password')
    ],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};

有人有答案吗?

谢谢

node.js authentication feathersjs
3个回答
0
投票

这似乎不起作用,至少使用@ feathersjs / authentication-local的当前版本1.2.9。

在verifier.js中,您将看到:

 // stuff omitted
_comparePassword (entity, password) {

 return new Promise((resolve, reject) => {
      bcrypt.compare(password, hash, function (error, result) {
        // Handle 500 server error.
        if (error) {
          return reject(error);
        }

        if (!result) {
          debug('Password incorrect');
          return reject(false); // eslint-disable-line
        }

        debug('Password correct');
        return resolve(entity);
      });
    });
  }

因此,默认验证程序始终使用硬编码的bcrypt.compare,而不是任何提供的散列函数。

我找到的唯一解决方案是扩展Verifier并覆盖_comparePassword。然后:app.configure(local({ Verifier: MyCustomVerifier }));将工作。


0
投票

你可以将一个对象传递给hashPassword,他们称之为options。选项可以有两个字段,passwordFieldhash

...    
create: [ hashPassword({passwordField: 'password', hash: hasherFunc}) ]
...

0
投票

使用羽毛库本身。这是目前最简单,最可靠的一个。

const hash = require("@feathersjs/authentication-local/lib/utils/hash");

await hash(req.body.password).then(result => { // Do anything });
© www.soinside.com 2019 - 2024. All rights reserved.