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 分钟前
【AI开发之Rust】第 12 课:并发模型与同步原语
开发语言·后端·rust
jnrjian7 分钟前
Domain sync job SCHEDULER 空白job
oracle
烈风逍遥10 分钟前
第四篇:AI 模块架构设计:多 Provider 切换、RAG 知识库与 Agent 编排
前端·后端·架构
Gopher_HBo24 分钟前
Cobra源码学习
后端
斯维赤43 分钟前
Spring AI | 结构化输出 & 多模态 一篇讲透
java·后端
程序员清风1 小时前
聊聊我的AI学习方法与思考!
java·后端·面试
右耳朵猫AI1 小时前
Node.js周刊2026W38 | 进程中断缺陷修复、Copilot 迁至 Rust、Node 新增 VFS
javascript·后端·node.js
摇滚侠1 小时前
《Spring Boot 3:高级与架构设计》第 2 章 IOC容器的高级机制 Environment 个人理解 4
java·spring boot·笔记·后端
名字还没想好☜1 小时前
Go 实现指数退避重试:context 取消、抖动 jitter 与什么时候别重试
后端·golang·go
青山木1 小时前
RocketMQ 入门到原理(六):可靠性全景
java·后端·中间件·架构·rocketmq