Websocket适配器中的NestJS依赖注入



我正在尝试验证和检查用户的权限,同时在NestJS应用程序中建立websocket连接。

我发现了这个建议使用NestJS Websocket适配器的讨论。您可以在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注入另外两个服务,UserServiceJwtService来检查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
}

For info,AuthService在另一个模块中,而不是定义Websocket的模块。我还尝试在当前模块中导入AuthService(及其依赖项),但没有帮助。

是否可以使用app.get()方法来使用该服务?

我可以通过使用app.resolve()而不是app.get()来解决DI问题

export class AuthenticatedSocketIoAdapter extends IoAdapter {
private authService: AuthService;
constructor(private app: INestApplicationContext) {
super(app);
app.resolve<AuthService>(AuthService).then((authService) => {
this.authService = authService;
});
}
}

这解决了AuthService中注入的jwtService未定义的问题。

最新更新