Authorization and the logOut Resolver
Explore how to implement authorization in a GraphQL API by reading user IDs from JWT cookies and passing them to resolvers. Learn to use these IDs to restrict actions like upvoting and linking data to users. Understand how to implement a logOut resolver that clears authentication cookies, ensuring secure session management. This lesson helps you build the foundation for authenticated interactions in your GraphQL backend.
So far, we’ve implemented setting a cookie in the login resolver and have configured Apollo Studio to send it back on every request. However, we don’t do anything with this cookie when we receive it back.
Now, we’ll see how to read a user ID from a cookie and use it in resolvers for authorization. We will also see how we can implement the logOut mutation.
Reading incoming cookies
Let’s see how we can check an incoming JWT token and extract a user ID from it if it’s valid. If we get a valid user ID from a request, we pass it to the resolvers that handle user IDs using the GraphQL context.
As a reminder, we’re currently creating a context with Express request and response objects.
To read our cookies, we should use the req.cookies field that contains all cookies sent in a request. We can get our cookie from it, which has been named authCookie.
If we print the value of this cookie, we’ll see ...