【发布时间】:2021-11-05 03:31:33
【问题描述】:
我正在尝试在 NestJS 应用程序中建立 websocket 连接时验证和检查用户的权限。
我找到了推荐使用NestJS Websocket adapter 的this discussion。您可以在options.allowRequest 回调中执行令牌验证,如下所示。
export class AuthenticatedSocketIoAdapter extends IoAdapter {
private readonly authService: AuthService;
constructor(private app: INestApplicationContext) {
super(app);
this.authService = app.get(AuthService);
}
createIOServer(port: number, options?: SocketIO.ServerOptions): any {
options.allowRequest = async (request, allowFunction) => {
const token = request.headers.authorization.replace('Bearer ', '');
const verified = this.authService.verifyToken(token);
if (verified) {
return allowFunction(null, true);
}
return allowFunction('Unauthorized', false);
};
return super.createIOServer(port, options);
}
}
但是,我在 websocket 适配器中的依赖注入存在问题。 IoAdapter 的构造函数有一个 INestApplicationContext 参数,我正在尝试使用 app.get(AuthService) 取回 AuthService,如上所示。
AuthService 注入另外两个服务,UserService 和 JwtService 来检查 JWT 令牌。我的问题是这些服务仍未在该上下文中定义。
@Injectable()
export class AuthService {
constructor(private usersService: UsersService, private jwtService: JwtService) {}
verifyToken(token: string): boolean {
// Problem: this.jwtService is undefined
const user = this.jwtService.verify(token, { publicKey });
// ... check user has permissions and return result
}
对于信息,AuthService 位于另一个模块中,而不是定义 Websocket 的模块。我还尝试在当前模块中导入 AuthService(及其依赖项),但这没有帮助。
是否可以使用app.get() 方法使用服务?
【问题讨论】:
标签: websocket dependency-injection service nestjs adapter