在我的 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);
}
}
这非常适合我的 post/get 方法。
但是现在我对网络套接字有一些需求,所以我尝试了以下方法:
@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);
}
}
但:
- 即使我没有连接,连接也会建立
- 用户未设置为我的请求
会是什么:
- 使用我的身份验证保护并接收匹配用户的方式?
- 对于进一步的消息,我是否应该在网关中保留一个 client.id <--> 我的用户的字典?或者有没有办法在每条消息中也接收用户?