私の 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);
}
}
これは、ポスト/取得メソッドで完全に機能します。
しかし、今ではWebソケットが必要なため、次のことを試しました。
@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 <--> ユーザーの辞書をゲートウェイに保持する必要がありますか? または、各メッセージでユーザーも受信する方法はありますか?