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

在刷新页面,访问成功。

相关推荐
用户990450177800927 分钟前
ruoyi-vue2集成flowable6.7.2后端篇
后端
qq_124987075332 分钟前
基于springboot框架的小型饮料销售管理系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·spring·毕业设计
Warren9835 分钟前
datagrip新建oracle连接教程
数据库·windows·云原生·oracle·容器·kubernetes·django
我命由我1234538 分钟前
Python Flask 开发:在 Flask 中返回字符串时,浏览器将其作为 HTML 解析
服务器·开发语言·后端·python·flask·html·学习方法
IT_陈寒1 小时前
JavaScript 性能优化:5个被低估的V8引擎技巧让你的代码提速50%
前端·人工智能·后端
嘟嘟w1 小时前
SQL注入是什么
数据库·sql·oracle
surtr11 小时前
数据库基础(数据库原理和应用)
数据库·sql·mysql·oracle·database
想用offer打牌1 小时前
数据库大事务有什么危害(面试版)
数据库·后端·架构
踏浪无痕1 小时前
别再只会用 Feign!手写一个 Mini RPC 框架搞懂 Spring Cloud 底层原理
后端·面试·架构
用户695619440371 小时前
前后端分离VUE3+Springboot项目集成PageOffice核心代码
后端