FeathersJS 身份验证停用用户

FeathersJS authentication deactivate user

我正在使用 FeathersJS 并且对它提供的身份验证感到满意。在这种情况下,它是本地 JWT。客户要求用户管理能够禁用某些功能。 Users 模型中有字段isDisabled,但很难弄清楚应该在何处执行检查以及如何设置它。

"@feathersjs/feathers": "^3.0.2", "@feathersjs/authentication": "^2.1.0", "@feathersjs/authentication-jwt": "^1.0.1", "@feathersjs/authentication-local": "^1.0.2",

这取决于您要检查的位置。您可以在 get 方法的用户服务上 customize the JWT verifier or create a hook

app.service('users').hooks({
  after: {
    get(context) {
      const user = context.result;

      if(user.isDisabled) {
        throw new Error('This user has been disabled');
      }
    }
  }
});

我直接在我的身份验证挂钩中这样做了:

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

const verifyIdentity = authenticate('jwt')

function hasToken(hook) {
  if (hook.params.headers == undefined) return false
  if (hook.data.accessToken == undefined) return false
  return hook.params.headers.authorization || hook.data.accessToken
}

module.exports = async function authenticate(context) {
  try {
    await verifyIdentity(context)
  } catch (error) {
    if (error instanceof NotAuthenticated && !hasToken(context)) {
      return context
    }
  }
  if (context.params.user && context.params.user.disabled) {
    throw new Error('This user has been disabled')
  }
  return context
}

你看我确实检查了刚刚加载的用户记录并抛出错误以防万一。由于此挂钩在 before:all 中被调用,因此在执行任何操作之前用户将被拒绝。

至于 feathers 4,您可以非常轻松地扩展您的身份验证策略。例如,如果我们希望用户只能登录并验证他们的 JWT,我们将在 authentication.ts (Typescript) 中执行以下操作:

import { Id, Query, ServiceAddons } from '@feathersjs/feathers';
import { AuthenticationService, JWTStrategy } from '@feathersjs/authentication';
import { LocalStrategy } from '@feathersjs/authentication-local';
import { expressOauth } from '@feathersjs/authentication-oauth';

import { Application } from './declarations';

declare module './declarations' {
  interface ServiceTypes {
    'authentication': AuthenticationService & ServiceAddons<any>;
  }
}

通过更改 getEntityQuery 扩展本地策略以仅包含活跃的用户。

class CustomLocalStrategy extends LocalStrategy {
  async getEntityQuery(query: Query) {
    return {
      ...query,
      active: true,
      $limit: 1
    };
  }
}

扩展 JWT 策略,将 getEntity() 更改为 return null 如果用户处于非活动状态

class CustomJWTStrategy extends JWTStrategy {
  async getEntity(id: Id) {
    const entity = await this.entityService.get(id);

    if (!entity.active) {
      return null;
    }

    return entity;
  }
}

export default function(app: Application): void {
  const authentication = new AuthenticationService(app);

  authentication.register('jwt', new CustomJWTStrategy());
  authentication.register('local', new CustomLocalStrategy());

  app.use('/authentication', authentication);
  app.configure(expressOauth());
}