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

时间:2018-04-04 20:03:25

标签: websocket graphql apollo wss subscriptions

我使用以下模式为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://'不起作用。

2 个答案:

答案 0 :(得分:0)

我为graphql-subscription Websocket安全连接制作了一个示例。

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

关键是您需要tlsssl凭据。

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

答案 1 :(得分:-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',
  });
});