DEV Community

Syed Abubakar
Syed Abubakar

Posted on

NextJS Authentication with WPGraphQL Quries

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:

  1. Installed WordPress
  2. Installed WPGraphQL
  3. 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

}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}`;
  }
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)