We are working on a new batch of GraphQL features. One of those is the ability to get your API protected by automated authorisation.
There’s a first version built that we are moving through testing and into a beta release. It’ll be part of beta releases until the release of 20.07.0. We are really keen to get feedback and make this the most useful feature it can be.
Docs and examples will also land pretty soon. But seeing as there’s been lots of interest in this sort of feature I’m putting up this page as a way of recording interest, discussion, feature requests etc.
Authorisation
Firstly, note that this is about authorisation (what you can do), not authentication (who are you) for the GraphQL API.
The basic workings go like this:
- you set up some mechanism that authenticates you app’s users and provides a signed JWT with claims about that user
- you add rules to your GraphQL schema that says who can do what and tell Dgraph the public key of the JWT’s signing authority
- at query/mutation time Dgraph will use the claims in the signed JWT to filter query results and protect mutations from unauthorised access.
Let’s say for example that you are building a todo application. It’s a simple schema, just users and todos.
type User {
username: String! @id
...
}
type Todo {
id: ID
owner: User
text: String @search(by: [term])
...
}
You want individual users to be able to see their own todos, but not the todos of other users. So you arrange for the authentication service to provide a JWT with a claim Username
and you update the schema with a rule to say that a user can only see a todo if they are the owner
type Todo @auth(
query: "queryTodo($Username: String) { owner(filter: { username: { eq: $Username } }) { id } } "
) {
...
}
The effect at query time of a query like:
query {
queryTodo(filter: { text: { anyofterms: "graphql" }}, first: 10) {
text
...
}
}
Is the todos that both match the user’s query and pass the auth rule. In this case, that’s 10 “graphql” todos owned by the user submitting the query.
The consumer of the API doesn’t need to know the rules, or write queries/mutations that are aware of them.
The rules look like graph queries because you can write any rule that you can express as a GraphQL query in Dgraph. That makes for super powerful rules that can take in multiple parameters from the JWT, do arbitrary search in the graph, join multiple conditions, etc.
Going further, you could add isPublic: Boolean
to todos and say that a user can query a todo if they own it or it’s public. You can say that users can only update the todos they own, etc.
We’ll post more examples and links to documentation as it comes online. However, if you’ve got questions, feature requests, etc please feel to be involved in the conversation.