Skip to main content
Version: v3.x

Set up a JWT for Testing

By default, your supergraph uses your Hasura Cloud authentication token, also known as a personal access token (PAT), for authentication. This is convenient for testing from the console but should not be used in an application or shared with others.

Instead, to test authentication you need to set up an AuthConfig object and then generate the corresponding token.

Step 1: Install the jwt-cli

Install the jwt-cli, which allows you to generate tokens from the command line. You can follow their list of installation instructions found here.

Step 2: Generate a random string

Generate a random string that we'll use as the JWT secret key:

In your teminal, run the following command
openssl rand -hex 16

Copy the value returned by the terminal.

Creating a random string

If you don't want to use openssl, you can use any other random string generators. The only requirement is that the string must be at least 32 characters.

Step 3: Set up your AuthConfig object

Set up an AuthConfig object in your project which uses this secret key.

In globals/metadata/auth-config.hml:
kind: AuthConfig
version: v2
definition:
mode:
jwt:
claimsConfig:
namespace:
claimsFormat: Json
location: "/claims.jwt.hasura.io"
key:
fixed:
algorithm: HS256
key:
value: "<insert-the-key-generated-in-previous-step>"
tokenLocation:
type: Header
name: Auth-Token

Step 4: Create a new supergraph build

Create a supergraph build using this AuthConfig.

From the root of your project, run:
ddn supergraph build create \
--description "use jwt-based authconfig" \
--supergraph supergraph.yaml

Step 5: Generate a JWT

For testing, you can use the jwt-cli to encode and generate a new token with the different claims written to match your testing needs.

Run the following with your own values:
jwt encode --secret="<secret-key>" '{"exp": 1739905122,"iat": 1708369122,"claims.jwt.hasura.io":{"x-hasura-default-role": "admin","x-hasura-allowed-roles":["admin"]}}'

In the example above, we're setting the following values:

  • The issued (iat) time as Feb. 19 2024, at 18:58:42 as a Unix epoch timestamp.
  • The expiration (exp) time as Feb. 18, 2025 at 18:58:42.
  • The default role as admin.
  • The allowed roles as admin.

For more information about the claims Hasura expects, check out this page.

Step 6: Test your AuthConfig

In the Hasura console, add the JWT generated by the console as the value of a new header called Auth-token on the GraphiQL explorer. You should now be able to execute queries with your custom JWT.

Using environment variables

If you're storing your secret key's value as an environment variable, ensure you've updated the subgraph.yaml in the globals subgraph to include this envMapping.