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

在刷新页面,访问成功。

相关推荐
nvd1110 分钟前
K3s + ArgoCD 中的密码管理
数据库·oracle·argocd
IT_陈寒25 分钟前
Python的列表拷贝坑得我原地打转
前端·人工智能·后端
山甫aa33 分钟前
日志技术 Logback + Slf4j —— 从零开始的 Web 后端学习
java·后端·学习·web·logback
SomeB1oody1 小时前
【RustyML入门】7.3. 性能调优与并行
开发语言·后端·机器学习·rust·教程
手握风云-1 小时前
Spring Cloud:分布式系统的“粘合剂”(六)
后端·spring·spring cloud
yours_Gabriel1 小时前
【一】数据库基础:SQL语句、函数、约束、多表查询、事务
数据库·sql·oracle
mengge.cloud2 小时前
0823Keepalived + LVS(DR) + MariaDB主主 小白完整实战教程
linux·运维·网络·oracle·负载均衡·mariadb·lvs
BingoGo2 小时前
NativePHP v4 让 Blade 构建原生 iOS 与 Android 界面
后端·php
程序员爱钓鱼2 小时前
Go 编程实战:闭包 Closure——函数如何记住外部变量
后端·google·go
JaguarJack2 小时前
NativePHP v4 让 Blade 构建原生 iOS 与 Android 界面
后端·php·服务端