GraphQL(6):认证与中间件

下面用简单来讲述GraphQL的认证示例

1 实现代码

在代码中添加过滤器:

完整代码如下:

复制代码
const express = require('express');
const {buildSchema} = require('graphql');
const grapqlHTTP = require('express-graphql').graphqlHTTP;
// 定义schema,查询和类型, mutation
const schema = buildSchema(`
    input AccountInput {
        name: String
        age: Int
        sex: String
        department: String
    }
    type Account {
        name: String
        age: Int
        sex: String
        department: String
    }
    type Mutation {
        createAccount(input: AccountInput): Account
        updateAccount(id: ID!, input: AccountInput): Account
    }
    type Query {
        accounts: [Account]
    }
`)

const fakeDb = {};

// 定义查询对应的处理器
const root = {
    accounts() {
        var arr = [];
        for(const key in fakeDb) {
            arr.push(fakeDb[key])
        }
        return arr;
    },
    createAccount({ input }) {
        // 相当于数据库的保存
        fakeDb[input.name] = input;
        // 返回保存结果
        return fakeDb[input.name];
    },

    updateAccount({ id, input }) {
        // 相当于数据库的更新
        const updatedAccount = Object.assign({}, fakeDb[id], input);
        fakeDb[id] = updatedAccount;
        // 返回保存结果
        return updatedAccount;
    }
}

const app = express();

const middleware = (req, res, next) => {
    if(req.headers.cookie==null){
        res.send(JSON.stringify({
            error: "您没有权限访问这个接口"
        }));
        return;
    }

    if(req.url.indexOf('/graphql') !== -1 && req.headers.cookie.indexOf('auth') === -1) {
        res.send(JSON.stringify({
            error: "您没有权限访问这个接口"
        }));
        return;
    }
    next();
}

app.use(middleware);

app.use('/graphql', grapqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))

app.listen(3000);

访问效果如下:

这边我直接在浏览器修改cookie,如下:

在刷新页面,访问成功。

相关推荐
未秃头的程序猿1 分钟前
分库分表一年后,我复盘了当时最该想清楚的三件事
java·数据库·后端
岁月如歌77864 分钟前
顺序消息与幂等消费完全指南:从队列有序到接口幂等
java·后端·架构
合橱瑰5 分钟前
从“假智能”到“真闭环”:Go 向量推理引擎的零硬编码调优实践
后端·go
SamDeepThinking5 分钟前
不改逻辑、不拆方法:仅靠「调整代码顺序」提升可读性
java·后端·程序员
泡海椒6 分钟前
适配老旧项目:JQuick-Java兼容Java8+环境改造迁移实战指南
后端
IT_陈寒8 分钟前
Java的HashMap竟然不是线程安全的,现在才知道!
前端·人工智能·后端
IT_陈寒9 分钟前
React hooks闭包陷阱让我加了一宿班
前端·人工智能·后端
不一样的少年_10 分钟前
设计稿里的图片明明很清晰,为什么到了手机上却糊了?一文讲透 DPR、压缩与格式选择
前端·后端·图片资源
卷无止境10 分钟前
当"精简主义"住进AI编程助手:Ponytail深度解读
后端·python·fastapi
兔子零102415 分钟前
我给 Pi Coding Agent 做了一个桌面控制台:Pi-Harness
前端·javascript·后端