我正在使用FeathersJS并且对它提供的身份验证感到满意。我这是本地JWT。客户端请求用户管理能够禁用某些功能。在用户模型中有字段isDisabled
,但很难确定应该在哪里执行检查以及如何设置它。
"@feathersjs/feathers": "^3.0.2",
"@feathersjs/authentication": "^2.1.0",
"@feathersjs/authentication-jwt": "^1.0.1",
"@feathersjs/authentication-local": "^1.0.2",
答案 0 :(得分:2)
这取决于您要检查的位置。您可以customize the JWT verifier或在get
方法的用户服务上创建hook:
app.service('users').hooks({
after: {
get(context) {
const user = context.result;
if(user.isDisabled) {
throw new Error('This user has been disabled');
}
}
}
});
答案 1 :(得分:1)
对于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
};
}
}
通过alter getEntity()
扩展JWT 策略以在用户不活动时返回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());
}
答案 2 :(得分:0)
我直接在我的身份验证挂钩中完成了此操作:
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
中调用了此钩子,因此在执行任何操作之前都会拒绝用户。