Overview
Now that we've seen how Airlock handles both authentication and authorization, we can take a step back and check that everything is working.
In this lesson, we will:
- Use GraphOS Studio to add headers to a GraphQL query and test our auth setup.
Testing a query in GraphOS Studio
Let's start by opening http://localhost:4000
in GraphOS Studio Sandbox.
We'll try out a query that requires an authenticated and authorized user: retrieving a host's listings. This query needs you to be logged in as a host.
Using Explorer, let's build a query to retrieve a host's listings. For each listing, we'll ask for the title
, costPerNight
, description
, photoThumbnail
, numOfBeds
, and locationType
.
Here's the complete query:
query GetHostListings {hostListings {titlecostPerNightdescriptionphotoThumbnailnumOfBedslocationType}}
Let's run the operation, and... uh oh! We get back an AuthenticationError
with no logged-in user š±
After a brief moment of panic, let's think about what we're missing.
We've just set up the server-side handling of Authorization headers, but we haven't actually sent those headers with our request! So our server is trying to authenticate the user sending the request, but it can't find their user token, and it returns the appropriate error.
Adding headers in GraphOS Studio
Let's go ahead and add those missing headers.
In the bottom panel of the Explorer, open the Headers tab.
Click the New header button. Set the header key as
Authorization
, and set the value asBearer user-1
. (We know thatuser-1
is a host!)
Authorization: Bearer user-1
Let's run the query again! Now that we have the correct header, we get the data we're asking for with all the fields we need.
For fun, let's check what happens if we ask for the exact same fields, but as a guest, like user-2
. Change the value of the Authorization
header to "Bearer user-2", then run the query.
We get a ForbiddenError
that says only hosts have access to listings. But we're logged in as a guest, so that's great! Our server is working as it's supposed to.
Key takeaways
- You can add headers to requests in GraphOS Studio Explorer via the Headers tab.
Conclusion
And with that, we've seen our first example of implementing auth on a GraphQL server! We learned how to use HTTP headers to authenticate users, how to write field-level authorization in a GraphQL resolver, and how to add headers to a request in GraphOS Studio.
If you're interested in digging deeper into auth topics, check out the list of additional resources below.
As for what's next, you can check out the Intermediate Schema Design side quest, or dive into the Voyage series to learn how to modularize your graph using Apollo Federation.