graphql - Fastify JWT 与 postgraphile 的使用
问题描述
我正在尝试使用 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);
}
});
任何帮助表示赞赏。
解决方案
问题:您正在使用 fastify 中间件功能fastify.use(postgraphile..
。
注册为中间件的函数在你添加逻辑的preValidation
钩子之前执行。
生命周期文档显示:您可以看到在中间件之前运行的唯一挂钩是,因此您应该更改:app.authenticate
onRequest
routeOptions.onRequest = [app.authenticate];
推荐阅读
- android - 使用导航控制器创建两次的片段
- apache-kafka - 如何使用 kafka-connect-datagen 为十进制字段(字节)生成数据?
- c++ - 将数据数组格式化为 multipart/form-data
- node.js - 通过将参数传递给 Postman 来对 Sequelize 进行排序的任何方法
- javascript - 在购物车底部添加我的倒计时
- docker - 错误 429:配额指标“查询”超出配额并限制“每个用户每分钟的查询数”
- node.js - localfield 为数组时如何使用聚合查找方法?
- asp.net-web-api - 使用 Gmail 和 Web Api 发送电子邮件失败
- python - 添加阴影以突出显示 matplotlib 中的重叠元素
- sql - 如何使用openjson交叉应用具有多个对象的json,例如: [{"id":"xxx","values":"xxx"},{"id":"zzz","values":"zzz" }]?