As a GraphQL API gives you a lot of extra power and possibilities, it also introduces some new attack vectors. Nothing prevents the user of your (web) application to open the developer console and start creating and sending other queries to your GraphQL backend. By using the authentication token already available, he/she can call your API. So without further mitigations a user can create and run any query he/she can think of.
Luckily there are multiple ways to control this attack vector. I already talked about
- Assigning a complexity budget.
- Limiting the query depth.
- Adding authorization
In this post I want to focus on a specific feature supported by most GraphQL api’s: persisted queries.
When using persisted queries, a client only sends a query identifier (and optionally variables) to the server instead of the full query text. This approach provides several benefits, such as reducing bandwidth usage, makes caching a lot easier and allows extra optimizations on the server.
From a security perspective you can configure the server to only accept persisted queries and refuse any other queries provided by a client. This gets rid of a whole suite of potential attack vectors, since malicious actors can no longer craft and execute harmful queries against your GraphQL server.
Let me show you how to implement this.
Persisted queries in the HotChocolate GraphQL Server
On the server-side we need to update our GraphQL configuration.
We first enable the persisted query pipeline and specify where HotChocolate should look for the persisted queries.
Remark: In the example above I load the persisted queries from disk. Other options exist(Redis, inmemory). I’ll explain later how we get the persisted query files on disk.
This is sufficient to start using the persisted queries feature and benefit from the performance advantage it offers. If we also want to use the security feature, we can block dynamic queries by adding the following line:
That’s all we need to do on the server-side. Let’s move on to the client…
Persisted queries in the Strawberry Shake GraphQL Client
On the client we need to update the csproj file and include the following:
Once we have done this, a query hash will be calculated and the content of the query will be copied to the specified folder. It is the content of this folder that is required on the server to check which persisted queries are available and can be used.
Remark: I’ll leave it up to you how you get the content of this folder to the server. We typically do this as a part of the build process.
If we now execute a query through the client:
the following information is send over the line:
If I try to execute another query that is not part of the persisted queries I get the following error message:
More information: