User authentication
Now that we can get the links saved, let's add a layer of security by using jsonwebtoken.
There are 2 important things you should always do:
Hash password before storing them in the database. If you leak them, you won't expose the actual passwords.

Only store enough information in the JWT to identify the user. Anyone can read its content.
Try it yourself, take this token and paste it in jwt.io.

Never store password in plain text.
Never put sensitive data in a JWT.
Install the required dependencies:
We first going to create a GraphQL input to structure the data we receive:
Update the User entity to return the jwt with:
Add your jwtSecret to the shared config:
And finally create the resolver:
Writing tests
Update setupTests.ts to require the environment variables:
When building the schema, GraphQL will complain if we don't have any queries. For this reason, let's create a Health resolver and add it to our schema when testing.
Finally, test the resolver:
Adding security to the links
How do we know which user just sent a request? GraphQL uses context to pass down information to all resolvers and we will use the Authorization header to send the JWT which each request.
Populating the GraphQL context
Testing
We can mock the context when creating the test server:
Getting the context from resolvers
Add the argument @Ctx() context to a resolver:
Adding headers in the playground
Use the tab HTTP HEADERS at the bottom left.

Conclusion
The backend is now ready to interact with the frontend. We can interact safely with the database and we have enough to implement anything we might need.
A lot is going on in this chapter. Have look at this Pull Request to see all the changes with comments.
Last updated
Was this helpful?