Context Middleware

The Context Middlewares uses Information provided by the request context object to rewirte a request. In the example below you'll understand how this feature can be used to secure a graphql backend that does not bring security out of the box.

By using the Context Middleware you can rewrite Graphql requests by annotating a schema and providing the necessary request context information.

Directive

To configure a schema use the following directive.

directive @addArgumentFromContext(
name: String!
contextKey: String!
) on FIELD_DEFINITION

Example

This example schema will rewrite Requests when a user wants to fetch documents. Keep in mind that the documents field within the Query type does not allow arguments.

example-schema
directive @addArgumentFromContext(
name: String!
contextKey: String!
) on FIELD_DEFINITION
scalar String
schema {
query: Query
}
type Query {
documents: [Document] @addArgumentFromContext(name: "user",contextKey: "user")
}
type Document implements Node {
owner: String
sensitiveInformation: String
}

The original query without arguments.

example-client-query
query myDocuments {
documents {
sensitiveInformation
}
}

In this case we'll manually add a Header to the request. It's up to an authentication middleware to set Headers as such.

example-client-headers
request.Header.Set("user", "jsmith@example.org")

Finally the rewritten query which gets sent to the backend graphql service. The header was translated into a field parameter. The user will only get data which he's allowed to fetch.

example-backend-query
query myDocuments {
documents(user: "jsmith@example.org") {
sensitiveInformation
}
}