The WPGraphQL plugin produces a public /graphql
endpoint that can be queried for any published content. Because I want control over where my content is displayed and by whom, I have added JSON Web Token authentication to this site’s build process.
WPGraphQL maintains this JWT Authentication plugin as a solution to authentication management. This plugin is installed in WordPress alongside the core WPGraphQL plugin and provides LoginUser
, RegisterUser
, and RefreshAuthToken
mutations. My application will need to use these mutations to access my site’s content after I go into the WPGraphQL plugin’s management panel and restrict my endpoint to authenticated users.
The WPGraphQL JWT Authentication plugin documentation does a good job explaining how these mutations work and provides a demo of their usage in a GraphiQL sandbox. Actually implementing them within my application took a bit of exploration and iteration before I could get a solution working end to end.
What follows are my implementation notes….
Environment variables & credentials
The username and password are provided by WordPress. To set this up securely, I created a WordPress user to manage the connection to my application. On the Account Management panel for this user account, all the way at the bottom is an application password generator.
I included the username and application password in my .env.local
file:
WORDPRESS_API_URL='https://your-domain.com/graphql'
WORDPRESS_USERNAME='wpgraphql_demo'
WORDPRESS_PASSWORD='vrya 2sGJ 8My1 TWOI VB1F ajz7'
These credentials are required by the WPGraphQL JWT Authentication mutations.
The JWToken authentication workflow
The JSON Web Tokens workflow is a self contained way to provide an authenticated user (in my case my web application’s build process is the user) with a secure token that can be included in content requests in order to confirm access permission.
As implemented in my site’s build code, each request to my GraphQL endpoint now runs the following workflow:
- The
fetchToken
request supplies theLoginUser
mutation and credentials. - Upon successful authentication, an
authToken
valid for < 300 seconds is returned and set as an HTTP Authorization header. - The subsequent
fetchAPI
request supplies a query for content. TheauthToken
in the HTTP Authorization header is used by the endpoint to authenticate this request prior to execution of the query. - Upon successful verification that the
authToken
is valid, site content is returned and compiled into the static website you are reading right now.