Implementing authentication
You'll almost always need to safeguard queries and mutations from unauthenticated and/or unauthorized users while implementing your GraphQL API. In this section, we'll add authentication with JWT to our GraphQL API.
In Apollo, we can retrieve the JWT token sent back by the client from the HTTP header, extract the user information from that token, and include it in the context, which can be accessed from any resolver. In the resolver, we can use the user's information to verify what data the user is authorized to access.
We'll be using libraries such as dotenv
for loading environment variables from a .env
file that we can use to add the secret required for generating JWTs, and jsonwebtoken
for generating the tokens. We'll also be using the Scrypt algorithm for hashing the users' passwords before saving them to the database.
Let's now see the practical steps:
- Let's get started by installing the required...