我正在尝试使用 fastify 服务器设置 postgraphile,它按预期工作。现在,我使用 fastify-jwt 插件将身份验证中间件添加到 postgraphile 公开的 graphql 端点,但是当我使用 graphql IDE 访问 graphql 端点时,我能够看到该方案并能够在没有授权标头的情况下查询数据。如何使 fastify-jwt 插件与 postgraphile 一起使用?
这是我的代码:
安装Postgraphile.js
const { postgraphile } = require('postgraphile');
const PgSimplifyInflectorPlugin = require('@graphile-contrib/pg-simplify-inflector');
module.exports = async function (fastify) {
fastify.log.info('Establishing PostgreSQL DB connection...');
await fastify
.use(
postgraphile(
'postgres://postgres:postgres@localhost:5432/demo',
'app_public',
{
dynamicJson: true,
appendPlugins: [PgSimplifyInflectorPlugin],
enhanceGraphiql: process.env.NODE_ENV !== 'production' ? true : false,
graphileBuildOptions: {
nestedMutationsSimpleFieldNames: true,
nestedMutationsDeleteOthers: false,
},
disableQueryLog: process.env.NODE_ENV !== 'production' ? true : false,
graphiql: process.env.NODE_ENV !== 'production' ? true : false,
watchPg: process.env.NODE_ENV !== 'production' ? true : false,
}
)
)
.ready((err) => {
if (err) return fastify.log.error(err);
});
};
服务器.js
const Fastify = require('fastify');
const helmet = require('fastify-helmet');
const cors = require('fastify-cors');
const JWT = require('fastify-jwt');
const fp = require('fastify-plugin');
const installPostgraphile = require('./installPostgraphile');
const app = Fastify({
logger: true,
});
// Register Plugins
app.register(cors);
app.register(helmet);
app.register(JWT, {
secret: 'supersecret',
});
app.post('/login', (req, reply) => {
// some code to authenticate
const token = instance.jwt.sign({ payload: { user: 'foo' } });
reply.send(token);
});
app.decorate('authenticate', async function (request, reply) {
try {
// Autorization logic
await request.jwtVerify();
} catch (err) {
reply.send(err);
}
});
app.addHook('onRoute', (routeOptions) => {
if (routeOptions.url === '/graphql') {
routeOptions.preValidation = [app.authenticate];
}
});
app.register(fp(installPostgraphile));
app.listen(process.env.PORT || 3000, (err) => {
if (err) {
app.log.error(err);
process.exit(1);
}
});
任何帮助表示赞赏。