我有下面的控制器。
@controller('/users')
class UsersController {
@httpGet('/', authMiddleware({ role: 'ADMIN' }))
public get() { ... }
}我实现了一个自定义AuthenticationProvider,它返回一个主体,其中包含有关当前已验证用户的详细信息,包括用户的角色。
....
return new Principal({
firstName: "John",
lastName: "Smit",
roles: ["ADMIN"]
});
...这一切都很好,但我想知道如何从上面的GET路由使用的authMiddleware中检索主体。
现在我有一个丑陋的技巧,它使用了InversifyJS的内部结构。
function authMiddlewareFactory() {
return (config: { role: string }) => {
return (
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
const httpContext: interfaces.HttpContext =
Reflect.getMetadata(
"inversify-express-utils:httpcontext",
req
);
const principal: interfaces.Principal = httpContext.user;
if (!principal.isInRole(config.role)) {
res.sendStatus(HttpStatus.UNAUTHORIZED);
return;
}
next();
};
};
}自定义身份验证提供程序使用authorization标头对用户进行身份验证,并返回主体。我不想在中间件中再次做这项工作,我只想检索主体。
这个攻击是有效的,但是我想知道是否有人知道在这个中间件中获得HttpContext的更干净的方法。
我知道如果从BaseMiddleware扩展,您可以访问HttpContext,从而访问主体(用户),但是我不清楚如何将配置(参数)传递给它,比如所需的角色。与InversifyJS上的以下问题相关。
发布于 2019-01-17 17:49:01
这不受支持,但我知道为什么需要它。我们不能将httpContext作为参数传递给中间件,因为我们希望保持标准Express中间件的兼容性。这意味着唯一的选择就是做一些你已经做过的事情,但理想情况下,我们应该使用一些帮助器来封装它。
我们需要实现类似如下的getHttpContext函数:
import * as express from "express";
import { getHttpContext } from "inversify-express-utils";
function authMiddlewareFactory() {
return (config: { role: string }) => {
return (
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
const httpContext = getHttpContext(req);
const principal: interfaces.Principal = httpContext.user;
if (!principal.isInRole(config.role)) {
res.sendStatus(HttpStatus.UNAUTHORIZED);
return;
}
next();
};
};
}在此实现之前,除了inversify内部的信息泄漏之外,我不认为您的实现有任何问题。
https://stackoverflow.com/questions/54218295
复制相似问题