GraphQL LogoGraphQL 中文网

身份验证和 Express 中间件

将任何 Express 中间件与 graphql-http 结合使用都很简单。特别是,这是处理身份验证的一个很好的结构。

英:It's simple to use any Express middleware in conjunction with graphql-http. In particular, this is a great pattern for handling authentication.

要将中间件与 GraphQL 解析器结合使用,只需像使用普通 Express 应用一样使用中间件即可。然后,request 对象可用作任何解析器中的第二个参数。

英:To use middleware with a GraphQL resolver, just use the middleware like you would with a normal Express app. The request object is then available as the second argument in any resolver.

例如,假设我们希望服务器记录每个请求的 IP 地址,并且我们还想编写一个返回调用者 IP 地址的 API。我们可以通过中间件来实现前者,通过访问解析器中的 request 对象来实现后者。这是实现此功能的服务器代码:

英:For example, let's say we wanted our server to log the IP address of every request, and we also want to write an API that returns the IP address of the caller. We can do the former with middleware, and the latter by accessing the request object in a resolver. Here's server code that implements this:

var express = require("express")
var { createHandler } = require("graphql-http/lib/use/express")
var { buildSchema } = require("graphql")
var schema = buildSchema(`
type Query {
ip: String
const loggingMiddleware = (req, res, next) => {
console.log("ip:", req.ip)
var root = {
ip: function (args, request) {
return request.ip
var app = express()
schema: schema,
rootValue: root,
graphiql: true,
console.log("Running a GraphQL API server at localhost:4000/graphql")

在 REST API 中,身份验证通常使用标头进行处理,标头包含一个身份验证令牌,用于证明用户正在发出此请求。Express 中间件处理这些标头并将身份验证数据放在 Express request 对象上。处理此类身份验证的一些中间件模块有 通行证express-jwtexpress-session。这些模块中的每一个都适用于 graphql-http

英:In a REST API, authentication is often handled with a header, that contains an auth token which proves what user is making this request. Express middleware processes these headers and puts authentication data on the Express request object. Some middleware modules that handle authentication like this are Passport, express-jwt, and express-session. Each of these modules works with graphql-http.

如果你不熟悉这些身份验证机制,我们建议使用 express-jwt,因为它很简单,而且不会牺牲任何未来的灵活性。

英:If you aren't familiar with any of these authentication mechanisms, we recommend using express-jwt because it's simple without sacrificing any future flexibility.

如果你已经线性阅读了文档并达到了这一点,那么恭喜你!你现在已经了解构建实用的 GraphQL API 服务器所需的一切。

英:If you've read through the docs linearly to get to this point, congratulations! You now know everything you need to build a practical GraphQL API server.

继续阅读 →构造类型
GraphQL 中文网 - 粤ICP备13048890号