1

認証済みソケット io.adapter.ts

export class AuthenticatedSocketIoAdapter extends IoAdapter {
  private readonly authService: AuthService;

  constructor(private app: INestApplicationContext) {
    super(app);
    this.authService = this.app.get(AuthService);
  }

  createIOServer(port: number, options?: SocketIO.ServerOptions): any {
    options.allowRequest = async (request, allowFunction) => {
      const { authorized, errorMessage } = await this.check(parse(request?.headers?.cookie || '').jwt, [UserRole.ADMIN]);
      if (!authorized) {
        return allowFunction(errorMessage, false);
      }

      return allowFunction(null, true);
    };


    return super.createIOServer(port, options);
  }

main.ts

const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: ['http://localhost:4200'],
    credentials: true
  });
  app.use(cookieParser());
  app.use(csurf({ cookie: true }));
  app.useWebSocketAdapter(new AuthenticatedSocketIoAdapter(app));

認証成功時: 認証成功

認可失敗時: 認可失敗

4

1 に答える 1