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

在刷新页面,访问成功。

相关推荐
bjzhang7525 分钟前
SpringCloud——国产化改造,项目对接 TongWeb 嵌入版
后端·spring·spring cloud
fen_fen32 分钟前
DB2表创建与Python插入、查询实操解析
数据库·oracle
光影少年40 分钟前
平时如何学习新技术?
后端·学习·前端框架
csdn2015_1 小时前
springboot controller 参数可以是List吗
spring boot·后端·list
keyborad pianist1 小时前
MySQl
数据库·mysql·oracle
Memory_荒年1 小时前
Dubbo调优实战:从QPS 1000到10000的惊险过山车之旅
java·后端·dubbo
Cosolar1 小时前
别再羡慕 Python 了!Java 开发者的 AI Agent 全指南:四大框架从选型到实战
java·人工智能·后端
来一斤小鲜肉1 小时前
Spring AI核心:高阶API之Tool Calling
后端·ai编程
糖猫猫_1 小时前
Kite 实现逻辑删除
后端·github
Memory_荒年1 小时前
Dubbo高级实战:从“能用”到“好用”的奇技淫巧
java·后端