使用Apollo和GraphQL设置安全(wss)websockets服务器
我正在使用以下模式为Apollo/GraphQL订阅设置WebSocket连接:使用Apollo和GraphQL设置安全(wss)websockets服务器,websocket,graphql,apollo,wss,subscriptions,Websocket,Graphql,Apollo,Wss,Subscriptions,我正在使用以下模式为Apollo/GraphQL订阅设置WebSocket连接: import express from 'express'; import { graphqlExpress, graphiqlExpress, } from 'apollo-server-express'; import bodyParser from 'body-parser'; import cors from 'cors'; import { execute, subscribe } from 'g
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://”不起作用。您需要使用
https
而不是http
包。
您还需要有证书。Eather是自签名的或来自证书颁发机构的
它可能是这样的:
从“https”导入{createServer};
...
//加载/获取证书
...
const wss=createServer(sslCredentails,server);
wss.listen(端口,()=>{
log(`Apollo Server现在正在运行https://localhost:${PORT}`);
//设置WebSocket以处理GraphQL订阅
新订阅服务器({
执行,,
订阅
模式
}, {
服务器:wss,
路径:'/subscriptions',
});
});代码>我为graphql订阅制作了一个示例
websocket安全连接
以下是链接:
关键是您需要tls
或ssl
凭据
对于开发,您可以使用openssl
生成自签名凭据,如何知道是否已经设置了wss?在我看来,它仍然找不到WSS有没有办法用JMeter之类的工具来测试它的性能?