4. Auth in Apollo Studio
2m

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 Apollo Studio to add headers to a GraphQL query and test our auth setup.

Testing a query in Apollo Studio

Let's start by opening http://localhost:4000 in Apollo 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 {
title
costPerNight
description
photoThumbnail
numOfBeds
locationType
}
}

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 Apollo Studio

Let's go ahead and add those missing headers.

  1. In the bottom panel of the Explorer, open the Headers tab.

  2. Click the New header button. Set the header key as Authorization, and set the value as Bearer user-1. (We know that user-1 is a host!)

A screenshot of the Apollo Studio Explorer. In the Headers tab at the bottom of the screen, there's a header called 'Authorization' with a value of 'Bearer user-1'.
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.

Task!

Key takeaways

  • You can add headers to requests in Apollo 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 Apollo 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.

Additional resources

Previous