【发布时间】:2022-12-24 01:33:05
【问题描述】:
在我的 NestJS API 中,我是 JWT 令牌,存储在 cookie 中以验证我的用户。
用户必须调用我的登录控制器:
@UseGuards(LocalAuthenticationGuard)
@Post('login')
async logIn(@Req() request: RequestWithUser) {
const { user } = request;
const cookie = this.authenticationService.getCookieWithJwtToken(user._id);
request.res?.setHeader('Set-Cookie', cookie);
return user;
}
LocalAuthenticatedGuard 验证用户名密码并填写用户请求,然后将 cookie 提供给客户端,并将与我的其他警卫一起验证是否有任何进一步的请求:
@Injectable()
export default class JwtAuthenticationGuard extends AuthGuard('jwt') {}
及其相关策略:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly configService: ConfigService,
private readonly userService: UsersService,
) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
(request: Request) => {
return request?.cookies?.Authentication;
},
]),
secretOrKey: configService.get('JWT_SECRET'),
});
}
async validate(payload: TokenPayload) {
return this.userService.getById(payload.userId);
}
}
这非常适合我的发布/获取方法。
但是现在我对网络套接字有一些需求,所以我尝试了以下方法:
@WebSocketGateway({
cors: {
origin: '*',
},
})
export class PokerGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer() server: Server;
private logger: Logger = new Logger('AppGateway');
@SubscribeMessage('msgToServer')
handleMessage(client: Socket, payload: string): void {
this.logger.log(`Client ${client.id} sent message: ${payload}`);
this.server.emit('msgToClient', payload);
}
afterInit(server: Server) {
this.logger.log('Init');
}
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
}
@UseGuards(JwtAuthenticationGuard)
handleConnection(
client: Socket,
@Req() req: RequestWithUser,
...args: any[]
) {
this.logger.log(`Client connected: ${client.id}`);
this.logger.log(client.handshake.query['poker-id']);
this.logger.log(req);
}
}
但:
- 即使我没有连接,连接也会建立
- 用户未设置为我的请求
会是什么:
- 如何使用我的auth guard并接收匹配的用户?
- 对于进一步的消息,我是否应该只在网关中保留 client.id <--> 我的用户的字典?或者有没有办法在每条消息中也接收用户?
【问题讨论】:
标签: authentication websocket nestjs nestjs-jwt nestjs-gateways