如何解决如何使用graphql和护照设置身份验证,但仍使用Playground
在向我们的后端Graphql服务器添加身份验证后,“ Schema”和“ Docs”在Graphql Playground中不再可见。将令牌添加到Playground中的“ HTTP头”时执行查询,在通过身份验证时可以正常运行,而在未通过用户身份验证时则不能正常运行。
我们从Apollo服务器禁用了内置的Playground,并使用中间件xlsx
来使用其他URL并绕过身份验证。现在,我们可以浏览到Playground并使用它,但是我们无法在其中读取“ Schema”或“ Docs”。
尝试启用graphql-playground-middleware-express
不能解决此问题。在introspection
的{{1}}中调用passport.authenticate()
会更好吗?还有一个名为passport-graphql的工具,但它与本地策略配合使用,可能无法解决问题。在致电Playground路线之前,我也tried setting the token in the header,但这没用。
对此我们有点迷茫。感谢您提供的任何见解。
相关代码:
Context
apollo-server
解决方法
感谢this SO answer,我终于知道了。关键不是要在Express上使用passport
作为中间件,而是要在Graphql Context
中使用它。
在下面的示例代码中,您可以看到在ApolloServer的getUser
中使用的Promise Context
进行护照身份验证。这样,在dev
模式下运行时,仍然可以访问Playground,并且仍然可以访问“ Schema”末尾的“ Docs”。
根据Apollo docs部分“在上下文中放置用户信息”,这也是首选方法。
// apollo.ts
passport.use(bearerStrategy)
const getUser = (req: Express.Request,res: Express.Response) =>
new Promise((resolve,reject) => {
passport.authenticate('oauth-bearer',{ session: false },(err,user) => {
if (err) reject(err)
resolve(user)
})(req,res)
})
const playgroundEnabled = ENVIRONMENT.mode !== 'production'
export const getApolloServer = async () => {
return new ApolloServer({
schema,context: async ({ req,res }) => {
const user = await getUser(req,res)
if (!user) throw new AuthenticationError('No user logged in')
console.log('User found',user)
return { user }
},introspection: playgroundEnabled,playground: playgroundEnabled,})
}
最好的是,您只需要两个函数即可工作:passport.use(BearerStrategy)
和passport.authenticate()
。这是因为未使用会话,因此我们不需要将其添加为Express中间件。
// index/ts
const app = express()
app.use(cors({ origin: true }))
;(async () => {
await createConnections()
const server = await getApolloServer()
server.applyMiddleware({ app,cors: false })
app.listen({ port: ENVIRONMENT.port },() => { console.log(`Server ready`) })
})()
我希望这可以帮助遇到相同问题的其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。