Handling Authentication and Authorization in GraphQL
@felixfbecker
Ryan Chenkie (@ryanchenkie) is a developer advocate at Auth0, a Google Developer Expert and teaches a lot about Angular and GraphQL.
Phoenix
Phoenix is a tool built by Auth0 that allows new employees to get permissions to the GitHub org, npm org, etc. by asking the Phoenix bot on Slack.
How to do authentication and authorization to GraphQL?
The usual response to this question from the GraphQL community is "However you want". The reason for that is that the GraphQL spec is not opnionated about auth.
API auth needs to answer a few questions:
Is the requested data private?
Does the request contain authentication/authorization information?
Is that information valid?
Typical auth in REST
Authentication in REST could look like this in an Express API:
We want something similar in GraphQL, but not like this:
We need something that
Isn't a catch-all
Gives us info on the authenticated user
Allows us to handle auth errors appropriately
First we need to verify authentication:
This example extracts a JWT from the request and attaches it to the request.
Now we can use the payload in our resolvers:
We can also do authorization checks:
This can get a bit repitive. One option to avoid that is to wrap resolvers:
We can check the JWT in the wrapper:
image
Custom Directives
What if we want to limit access to specific fields? Custom directives give our queries more power: