0

我可以在 get 或 post 调用中访问请求标头

fastify.get('/route1',(req,res,next)=>{
  console.log(req.headers.Authorization)
  ...
}

我正在寻找一种将其传递给插件注册调用的方法,特别是fastify-graphql

const { graphqlFastify } = require("fastify-graphql");
fastify.register(graphqlFastify,
         {
            prefix: "/graphql",
            graphql: {
                schema: schema,
                rootValue: resolvers,
                context:{auth:req.headers.Authorization}    <-----
            }
        },
        err => {
            if (err) {
                console.log(err);
                throw err;
            }
        }
 );

有没有办法编写包装器或任何想法?

4

2 回答 2

0

对于需要在 graphql 上下文中访问请求标头的任何人,请尝试 graphql-fastify

用法

Create /graphql endpoint like following

const graphqlFastify = require("graphql-fastify");

fastify.register(graphqlFastify, {
    prefix: "/graphql",
    graphQLOptions
});

graphQLOptions

graphQLOptions 可以作为对象或返回 graphql 选项的函数提供

graphQLOptions: {
    schema: schema,
    rootValue: resolver
    contextValue?: context
}

如果是函数,则可以访问 http 请求和响应。这允许您进行身份验证并将身份验证范围传递给 graphql 上下文。看下面的伪代码

const graphQLOptions = function (request,reply) {
    const auth = decodeBearerToken(request.headers.Authorization);
    // auth may contain userId, scope permissions

    return  {
         schema: schema,
         rootValue: resolver,
         contextValue: {auth}
     }
});

这样,解析器函数可以访问 context.auth,从而允许您在继续之前检查用户的范围/权限。

于 2019-02-14T00:15:47.707 回答
0

我认为你不能那样做。

如果阅读代码你会发现:

因此,我认为您应该使用标准 JWT 检查身份验证客户端,然后使用另一个令牌服务器端。

最终的解决方案可能是检查 Apollo 2.0 并在 fastify-graphql 上打开问题。

这里有一个解释这个想法的小片段:

const fastify = require('fastify')({ logger: true })
const { makeExecutableSchema } = require('graphql-tools')
const { graphiqlFastify, graphqlFastify } = require('fastify-graphql');


const typeDefs = `
type Query {
    demo: String,
    hello: String
}
`
const resolvers = {
  Query: {
    demo: (parent, args, context) => {
      console.log({ args, context });
      return 'demo'
    },
    hello: () => 'world'
  }
}

const schema = makeExecutableSchema({ typeDefs, resolvers })

fastify.register(graphqlFastify, {
  prefix: '/gr',
  graphql: {
    schema,
    context: function () {
      return { serverAuth: 'TOKEN' }
    },
  },
});

fastify.listen(3000)

// curl -X POST 'http://localhost:3000/gr' -H 'Content-Type: application/json' -d '{"query": "{ demo }"}'
于 2019-02-12T15:24:29.420 回答