WPGraphQL is a GraphQL API that allows you to get data from your WordPress website. It allows us to separate the experience of controlling our content, which we do with WordPress.
By Default GrahpQL api endpoint is open, It means anyone with the link can access the API.
In this article we will look at implementing NextJs authentication with WPGraphQL so we can make our API calls secure.
We will be using WPGraphQL JWT Authentication to make the auth token.
Prerequisites:
- Installed WordPress
- Installed WPGraphQL
- Setup of NextJs with WordPress
Install, Activate & Setup
Let's start with installing WPGraphQL JWT Authentication. Open the link and Download the .zip from Github and add to your plugins directory, then activate the plugin.
JWT uses a Secret token defined on the server to validate the signing of tokens.
Generate your secret token from WordPress Secret Token and copy the NONCE_SALT.
Next Step is to define the secret token. You can define a Secret in WordPress file wp-config.php or Or you can use the filter graphql_jwt_auth_secret_key to set a Secret.
Add your secret token and paste below line in wp-config:
define( 'GRAPHQL_JWT_AUTH_SECRET_KEY', 'your-secret-token' );
for filter:
add_filter( 'graphql_jwt_auth_secret_key', function() {
return 'your-secret-token';
});
This secret is used in the encoding and decoding of the JWT token. If you wanted to invalidate all user, you can change the Secret on the server and all previously issued tokens would become invalid and require users to re-authenticate.
Open graphql IDE from WordPress run the query below to generate refresh token.
mutation LoginUser {
login(
input: {clientMutationId: "uniqueId",
username: "wordpress username",
password: "wordpress password"}
)
refreshToken
}
The refreshToken that is received in response is what we need in our NextJs application.
Open your nextJs application and add an entry in your .env.local file
WORDPRESS_AUTH_REFRESH_TOKEN=your-refresh-token
Open the api.js file inside the lib folder you'll see the AUTH code is already added by nextJs and it will add the secret with all your requests
if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
headers[
"Authorization"
] = `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`;
}
The final step is Restrict Endpoint to Authenticated Users. From your WordPress dashboard open GraphQL settings and check this option "Restrict Endpoint to Authenticated Users" and click save changes.
Happy coding :)
Read More:
Free Cloud Storage and Cloud Storage API
Best User Behavior Analytics Tools
Best IDaaS Service Providers 2021
Top comments (1)
Thank you for this tutorial. However, I am confused as it seems as though we are saving the refresh token for 1 authenticated user. What if we want to pass the refresh token as a variable that was saved as a HTTP cookie for every different user that logs in?