问题描述
我使用的护照本地策略非常适合快递:
I'm using a passport local strategy that works well with express:
passport.use(localStrategy);
passport.serializeUser((user, done) => done(null, JSON.stringify(user)));
passport.deserializeUser((obj, done) => done(null, JSON.parse(obj)));
app.use(passport.initialize());
app.use(passport.session());
此localStrategy正在执行Mongoose调用,以根据用户的pubKey来获取用户,我想以这种方式填充了request.user.
This localStrategy is doing a Mongoose call to get the user based on his pubKey and I guess that request.user is populated by this way.
我这样设置我的graphql端点:
I setup my graphql endpoint like this:
app.use('/graphql', bodyParser.json(), graphqlExpress(request => ({
debug: true,
schema,
context: {
user: request.user,
req: request,
},
formatError: (e) => {
console.log(JSON.stringify(e, null, 2));
return e;
},
})));
我的订阅方式是:
const ws = createServer(app);
// Run the server
ws.listen(settings.APP_PORT, () => {
console.log(`App listening on port ${settings.APP_PORT}!`);
// Set up the WebSocket for handling GraphQL subscriptions
new SubscriptionServer({
execute,
subscribe,
schema,
onConnect: (connectionParams, webSocket) => {
console.log(webSocket.upgradeReq);
return { user: connectionParams };
},
}, {
server: ws,
path: '/subscriptions',
});
});
我的会话在graphql查询和突变方面运行良好.但是我的订阅没有.
My session is working well on graphql queries and mutations. But not with my subscriptions.
我的目标是在我的订阅解析器上下文中访问我的用户会话.我可能需要在onConnect中访问诸如request.user之类的内容以填充上下文,但是我不知道该怎么做.
My goal is to have access to my user session in my subscription resolver context. I may need to access something like request.user in onConnect to populate the context, but I don't know how to do.
推荐答案
因此,经过一番修补,我发现您需要做的基本上是运行为套接字upgradeReq
重新创建passport
的所有内容.重新运行中间件:
So after some tinkering I've figured out that what you need to do is basically run the everything that recreates the passport
for the socket's upgradeReq
by re-running the middleware:
// Start with storing the middleware in constants
const passportInit = passport.initialize();
const passportSession = passport.session();
app.use(passportInit);
app.use(passportSession);
...
// Now populate the request with the upgradeReq using those constants
onConnect: (connectionParams, webSocket) => new Promise((resolve) => {
passportInit(webSocket.upgradeReq, {}, () => {
passportSession(webSocket.upgradeReq, {}, () => {
resolve(webSocket.upgradeReq);
});
});
}),
如果使用的是express-session
,则需要将其添加到上面.
If you are using an express-session
you need to add that to the above.
这篇关于如何使用带护照和快速会话的subscriptions-transport-ws的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!