使用Apollo和GraphQL设置安全(wss)websockets服务器

问题描述 投票:0回答:2

我使用以下模式为Apollo / GraphQL订阅设置websockets连接:

import express from 'express';
import {
  graphqlExpress,
  graphiqlExpress,
} from 'apollo-server-express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { execute, subscribe } from 'graphql';
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';

import { schema } from './src/schema';

const PORT = 3000;
const server = express();

server.use('*', cors({ origin: `http://localhost:${PORT}` }));

server.use('/graphql', bodyParser.json(), graphqlExpress({
  schema
}));

server.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
  subscriptionsEndpoint: `ws://localhost:${PORT}/subscriptions`
}));

// Wrap the Express server
const ws = createServer(server);
ws.listen(PORT, () => {
console.log(`Apollo Server is now running on http://localhost:${PORT}`);
  // Set up the WebSocket for handling GraphQL subscriptions
  new SubscriptionServer({
    execute,
    subscribe,
    schema
  }, {
    server: ws,
    path: '/subscriptions',
  });
});

如何更改连接以使用安全的websockets协议?简单地将'ws://'更改为'wss://'不起作用。

websocket graphql apollo wss subscriptions
2个回答
0
投票

我为graphql-subscription websocket安全连接做了一个样本。

这是链接:https://github.com/mrdulin/apollo-server-express-starter/tree/master/src/subscription/wss-with-nodejs-server

关键是你需要tlsssl凭证。

对于开发,您可以使用openssl生成自签名凭据。


-1
投票

您需要使用https而不是http包。您还需要有证书。收集自签名或来自证书颁发机构。

它可能看起来像这样:

import { createServer } from 'https';

...

// load / get certificate

...

const wss = createServer(sslCredentails, server);
wss.listen(PORT, () => {
console.log(`Apollo Server is now running on https://localhost:${PORT}`);
  // Set up the WebSocket for handling GraphQL subscriptions
  new SubscriptionServer({
    execute,
    subscribe,
    schema
  }, {
    server: wss,
    path: '/subscriptions',
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.