Links
Comment on page

JWT Authentication

Access the Graphlit Data API with a JSON Web Token (JWT).
The API uses the GraphQL query language, which supports client libraries for most programming languages.
To authenticate to the Graphlit Data API, you will need a JSON Web Token, or JWT for short.
On the Project Settings page of the Graphlit Developer Portal, you will find the Environment ID, Organization ID, and JWT Secret for the Environments, which have been provisioned for each Project.
Depending on your programming language, there are different approaches to create the JWT.
Javascript
Python
C#
You will need a Javascript JWT library to create and sign tokens. In this guide, we'll use the jsonwebtoken library in Node.js for illustrative purposes. Please adapt the instructions to your chosen library.
Install the jsonwebtoken library in your Node.js project with this command:
npm install jsonwebtoken
Creating and Signing a JWT
After installing the necessary library, use the following steps to create and sign a JWT:
  • Configure the Graphlit organization and environment IDs
  • Configure the JWT secret signing key for the Graphlit environment
  • Specify the expiration date/time of the JWT
  • Create the security key
  • Create the JWT signing credentials
The HMAC SHA256 (aka HS256) signing algorithm is required for the signing credentials. More information on JWT signing can be found here.
  • Create the required Graphlit claims
  • Create the JWT and write to a string
Verifying a JWT
You can verify the JWT using the same secret used to sign it. Below is an example in Node.js using the jsonwebtoken library:
const decoded = jwt.verify(token, secret);
console.log(decoded);
This will print the decoded JWT to the console. If the JWT was modified or if it has expired, jwt.verify will throw an error.
Code Sample
Here is a Javascript code sample to start with:
const jwt = require("jsonwebtoken");
// Replace these with your own values from the Graphlit environment
const secret = "YOUR_SECRET_KEY";
const environmentId = "YOUR_ENVIRONMENT_ID";
const organizationId = "YOUR_ORGANIZATION_ID";
// Specify your role (Owner, Contributor, Reader)
const role = "YOUR_ROLE";
// Define the payload
const payload = {
"https://graphlit.io/jwt/claims": {
"x-graphlit-environment-id": environmentId,
"x-graphlit-organization-id": organizationId,
"x-graphlit-role": role,
},
exp: Math.floor(Date.now() / 1000) + 60 * 60, // 1 hour from now
iss: "graphlit",
aud: "https://portal.graphlit.io",
};
// Sign the JWT
const token = jwt.sign(payload, secret);
// Use JWT to call the GraphQL API
In Python, you can sign your JWTs with the pyJWT library.
pip install pyjwt
Here's a Python code sample:
import jwt
import datetime
# Define your secret key, environment ID and organization ID
secret_key = "YOUR_SECRET_KEY"
environment_id = "YOUR_ENVIRONMENT_ID"
organization_id = "YOUR_ORGANIZATION_ID"
# Define the issuer and audience
issuer = "graphlit"
audience = "https://portal.graphlit.io"
# Specify the role (Owner, Contributor, Reader)
role = "Owner"
# Specify the expiration (one hour from now)
expiration = datetime.datetime.utcnow() + datetime.timedelta(hours=1)
# Define the payload
payload = {
"https://graphlit.io/jwt/claims": {
"x-graphlit-environment-id": environment_id,
"x-graphlit-organization-id": organization_id,
"x-graphlit-role": role,
},
"exp": expiration,
"iss": issuer,
"aud": audience,
}
# Sign the JWT
token = jwt.encode(payload, secret_key, algorithm="HS256")
# Use JWT to call the GraphQL API
# ...
# Verify the JWT
try:
decoded = jwt.decode(token, secret_key, algorithms=["HS256"], audience=audience)
print(decoded)
except jwt.ExpiredSignatureError:
print("Error: Token has expired")
except jwt.InvalidTokenError:
print("Error: Invalid token")
Please replace YOUR_SECRET_KEY, YOUR_ENVIRONMENT_ID, and YOUR_ORGANIZATION_ID with your own secret key, environment ID, and organization ID, respectively.
In C# you can use the System.IdentityModel.Tokens.Jwt namespace to create and sign JWTs. This library is part of the Microsoft.IdentityModel.Tokens NuGet package.
You'll need to install the System.IdentityModel.Tokens.Jwt NuGet package to your project. You can do this by running the following command in your Package Manager Console:
Install-Package System.IdentityModel.Tokens.Jwt
Creating and Signing a JWT
After installing the necessary package, use the following steps to create and sign a JWT:
  • Configure the Graphlit organization and environment IDs
  • Configure the JWT secret signing key for the Graphlit environment
  • Specify the expiration date/time of the JWT
  • Create the security key
  • Create the JWT signing credentials
The HMAC SHA256 (aka HS256) signing algorithm is required for the signing credentials. More information on JWT signing can be found here.
  • Create the required Graphlit claims
  • Create the JWT and write to a string
Code Sample
Here is a C# code sample to start with:
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
// Define your secret key, environment ID and organization ID
string secretKey = "YOUR_SECRET_KEY";
string environmentId = "YOUR_ENVIRONMENT_ID";
string organizationId = "YOUR_ORGANIZATION_ID";
// Define the issuer and audience
string issuer = "graphlit";
string audience = "https://portal.graphlit.io";
// Specify the role (Owner, Contributor, Reader)
string role = "Owner";
// Specify the expiration (one hour from now)
DateTime expiration = DateTime.UtcNow.AddHours(1);
// Create the security key
var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secretKey));
// Create the signing credentials
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
// Create the claims
var claims = new Claim[]
{
new Claim("https://graphlit.io/jwt/claims", JsonConvert.SerializeObject(new Dictionary<string, string>
{
["x-graphlit-environment-id"] = environmentId,
["x-graphlit-organization-id"] = organizationId,
["x-graphlit-role"] = role
}, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None }),
JsonClaimValueTypes.Json)
};
// Create the JWT and write it to a string
var token = new JwtSecurityToken(issuer, audience, claims, expires: expiration, signingCredentials: signingCredentials);
string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
// Use JWT to call the GraphQL API
Please note that YOUR_SECRET_KEY, YOUR_ENVIRONMENT_ID, and YOUR_ORGANIZATION_ID are placeholders. Replace these with your own secret key, environment ID, and organization ID, respectively.
When developing, you can use a user secrets strategy to protect your secrets.

Security Considerations

Be sure to keep your secret key private. If someone else obtains it, they can create and verify JWTs as if they were you, leading to potential security breaches.
Your secrets should always be stored as environment variables. Never hard-code them in your codebase or commit them to a repository.