向我们的后端 Graphql 服务器添加身份验证后,“Schema”和“Docs”在 Graphql Playground 中不再可见。向 Playground 中的“HTTP HEADERS”添加令牌时执行查询在经过身份验证而不是在用户未经过身份验证时可以正常工作,所以没关系。
我们禁用了 Apollo-server 的内置 Playground,并使用中间件graphql-playground-middleware-express
来使用不同的 URL 并绕过身份验证。我们现在可以浏览到 Playground 并使用它,但我们无法读取那里的“Schema”或“Docs”。
尝试启用introspection
并没有解决这个问题。调用ofpassport.authenticate()
会更好吗?还有一个名为passport-graphql的工具,但它适用于本地策略,可能无法解决问题。在调用 Playground 路由之前,我还尝试在标头中设置令牌,但这不起作用。Context
apollo-server
我们对此有点迷茫。感谢您为我们提供的任何见解。
相关代码:
// index/ts
import passport from 'passport'
import expressPlayground from 'graphql-playground-middleware-express'
const app = express()
app.use(cors({ origin: true }))
app.get('/playground', expressPlayground({ endpoint: '/graphql' }))
app.use(passport.initialize())
passport.use(bearerStrategy)
app.use(
passport.authenticate('oauth-bearer', { session: false }),
(req, _res, next) => { next() }
)
;(async () => {
await createConnections()
const server = await new ApolloServer({
schema: await getSchema(),
context: ({ req }) => ({ getUser: () => req.user, }),
introspection: false,
playground: false,
})
server.applyMiddleware({ app, cors: false })
app.listen({ port: ENVIRONMENT.port }, () => { console.log(`Server ready`) })
})()
// passport.ts
import { IBearerStrategyOptionWithRequest, BearerStrategy, ITokenPayload } from passport-azure-ad'
import { Account } from '@it-portal/entity/Account'
export const bearerStrategy = new BearerStrategy( config,
async (token: ITokenPayload, done: CallableFunction) => {
try {
if (!token.oid) throw 'token oid missing'
const knownAccount = await Account.findOne({ accountIdentifier: token.oid })
if (knownAccount) return done(null, knownAccount, token)
const account = new Account()
account.accountIdentifier = token.oid
account.name = token.name
account.userName = (token as any).preferred_username
const newAccount = await account.save()
return done(null, newAccount, token)
} catch (error) {
console.error(`Failed adding the user to the request object: ${error}`)
}
}
)