gpt4 book ai didi

node.js - 将 HttpContext 注入(inject) InversifyJS 中间件

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:02 24 4
gpt4 key购买 nike

我有以下 Controller 。

@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();
};
};
}

自定义身份验证提供程序使用授权 header 对用户进行身份验证并返回主体。我不想在中间件中再次执行此工作,我只想检索主体。

这个 hack 有效,但我想知道是否有人知道在这个中间件中获取 HttpContext 的更简洁的方法。

我知道如果您从 BaseMiddleware 扩展,您可以访问 HttpContext 以及主体(用户),但是我不清楚如何将配置(参数)传递给它,例如所需的角色。与 InversifyJS 上的以下问题相关。

https://github.com/inversify/InversifyJS/issues/673

最佳答案

这不受支持,但我明白为什么需要它。我们不能将 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 内部的信息泄漏之外,我没有发现您的实现有任何问题。

关于node.js - 将 HttpContext 注入(inject) InversifyJS 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54218295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com