我有一个解析应用程序,我想在每个请求中发送 sessionToken,以便我知道哪个用户正在访问什么。就像这篇文章提到的那样。
How to build a web app with GraphQL + parse.com?
丹尼尔留下了这条评论,我似乎无法做他提到的事情。
If the user has signed in on the client, you could potentially pass up a session token to the server to allow for the parse queries to be made with that session token (for ACL reasons).
在Relay中,我看到你可以通过headers
将sessionToken注入(inject)到networkLayer中,
但在我的 graphql 服务器中,我似乎无法通过 rootValue 属性访问此 sessionToken 和对 graphql 的热情。
有人知道如何使用解析服务器和身份验证吗?
F8 应用程序目前已将其标记为 TODO
,但我无法弄清楚这一点。
最佳答案
Express-Graphql supports a context
option它将作为最后一个参数传递给所有解析器函数。您可以将 Parse session token 作为 header 传递给任何 /graphql
请求,然后通过 context
转发该请求,如下所示:
import graphqlHTTP from 'express-graphql';
const app = express();
app.use('/graphql', graphqlHTTP((req) => ({
// ...
context: {
parseSessionToken: req.headers['parse-session-token'],
},
})));
现在,在解析器函数中,您可以在查询中使用此 token ,以确保强制执行适当的 ACL:
function resolve (_, args, context) {
return new Parse.Query('MyClass')
.first({ sessionToken: context.parseSessionToken });
}
如果您在客户端使用 Relay,请使用 Relay.injectNetworkLayer
像这样包含此 header :
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('http://example.com/graphql', {
headers: {
'parse-session-token': Parse.User.current().getSessionToken(),
},
})
);
如果您使用 Apollo 客户端,请使用 createNetworkInterface
在中间件函数中提供 header :
import ApolloClient, { createNetworkInterface } from 'apollo-client';
const networkInterface = createNetworkInterface('http://example.com/graphql');
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
req.options.headers['parse-session-token'] = Parse.User.current().getSessionToken();
next();
}
}]);
const client = new ApolloClient({
networkInterface,
});
关于session - 如何使用解析 session token 通过 graphql 发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37167622/