首页 > 解决方案 > 尝试使用 feathers.js 登录时如何获取特定错误

问题描述

每当我尝试使用正确的用户和正确的密码登录时,一切都很好,但是每当我尝试使用不存在的用户或错误的密码登录时,我都会遇到同样的错误:

{
  "name": "NotAuthenticated",
  "message": "Invalid login",
  "code": 401,
  "className": "not-authenticated",
  "errors": {}
}

预期的结果是显示:用户不存在。或者例如:给定的用户和密码不匹配

这是我在我的代码上所做的

var username = "givenUsername"
var password = "givenPassword"

 client.authenticate({
  strategy: 'local',
  username, password
}).then((authResponse)=>{
  console.log(authRersponse)
}).catch((err)=>{
  console.error(err)
})

标签: feathersjsfeathers-authentication

解决方案


默认情况下不会这样做,因为它会让攻击者猜测在您的系统上注册了哪些电子邮件地址或用户名。您始终可以自定义本地身份验证策略以抛出您想要的错误,例如通过覆盖findEntitycomparePassword

const { AuthenticationService, JWTStrategy } = require('@feathersjs/authentication');
const { LocalStrategy } = require('@feathersjs/authentication-local');
const { NotAuthenticated } = require('@feathersjs/errors');

class MyLocalStrategy extends LocalStrategy {
  async findEntity(username, params) {
    try {
      const entity = await super.findEntity(username, params);
      
      return entity;
    } catch (error) {
      throw new Error('Entity not found');
    }
  }

  async comparePassword(entity, password) {
    try {
      const result = await super.comparePassword(entity, password);
      
      return result;
    } catch (error) {
      throw new Error('Invalid password');
    }
  }
}

module.exports = app => {
  const authService = new AuthenticationService(app);

  authService.register('local', new MyLocalStrategy());

  // ...
  app.use('/authentication', authService);
}

推荐阅读