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,如下:

在刷新页面,访问成功。

相关推荐
IT_陈寒1 小时前
Java静态变量初始化坑得我头皮发麻
前端·人工智能·后端
步行cgn2 小时前
Thymeleaf 编辑表单详解:从字段回填到模拟 PUT 请求
后端
猫咪很可爱2 小时前
Oracle ORA-4031 错误分析与处理:SGA 内存不足导致 update/exp/expdp 失败
数据库·oracle
Song_RsHt3 小时前
Redis 与微服务,什么场景下无可替代
java·redis·后端·学习·微服务
学长毕设3 小时前
基于SpringBoot的建筑材料管理系统-附源码
java·spring boot·后端
程序员cxuan3 小时前
掀桌子了!Kimi K3.1 Pro 这效果也太离谱了。
人工智能·后端·程序员
摸爬滚打的小李3 小时前
关于 Arthas
java·后端
武子康4 小时前
黑图、彩色噪声、NaN、偏色怎么排查
人工智能·后端·agent
苏三说技术4 小时前
企业智能知识库 Python 后端实战:FastAPI + RAG + KAG 企业级 AI 项目
后端
Mk598784 小时前
从跑通到上生产:AgentScope-Java 六篇实战收官盘点
后端