Generate a JWT

Learn how to create a JSON Web Token (JWT) to authenticate to certain REST API endpoints with your ICR App.

About JSON web tokens (JWTs)

In order to authenticate as an app or generate an installation access token, you must generate a JSON Web Token (JWT). If a REST API endpoint requires a JWT, the documentation for that endpoint will indicate that you must use a JWT to access the endpoint.

Your JWT must be signed using the RS256 algorithm and must contain the following claims.

Claim
Meaning
Details

iat

Issued At

The time that the JWT was created. To protect against clock drift, we recommend that you set this 60 seconds in the past and ensure that your server's date and time is set accurately (for example, by using the Network Time Protocol).

exp

Expires At

The expiration time of the JWT, after which it can't be used to request an installation token. The time must be no more than 10 minutes into the future.

iss

Issuer

The ID of your ICR App. This value is used to find the right public key to verify the signature of the JWT. You can find your app's ID on the app's dashboard

alg

Message authentication code algorithm

This should be RS256 since your JWT must be signed using the RS256 algorithm.

To use a JWT, pass it in the Authorization header of an API request. For example:

curl --request GET \
--url "https://api.carbonregistry.com/projects" \
--header "Authorization: Bearer YOUR_JWT" 

Generating a JWT

Most programming languages have a package that can generate a JWT. In all cases, you must have a private key and the ID of your ICR App. For more information about generating a private key, see "Managing private keys for ICR Apps". You can find your app's ID on the app's dashboard.

import jwt from "jsonwebtoken";

interface CustomClaims {
  iss: string; // Issuer
  exp: number; // Expiration Time (Unix timestamp)
  iat: number; // Issued At (Unix timestamp)
  alg: string; // Algorithm
}

export function createJWT(): string {
  const claims: CustomClaims = {
    iss: process.env.NEXT_PUBLIC_APP_ID, // Replace with your ICR App's ID
    exp: Math.floor(Date.now() / 1000) + 600, // 10 minutes in the future
    iat: Math.floor(Date.now() / 1000) - 60, // 60 seconds in the past
    alg: "RS256",
  };

  // Create a JWT token
  const token = jwt.sign(claims, process.env.PRIVATE_KEY, {
    algorithm: "RS256",
  });
  return token;
}
const jwtToken = createJWT();
console.log("Generated JWT:", jwtToken);

The python script will prompt you for the file path where your private key is stored and for the ID of your app. Alternatively, like in the typescript example, you can pass those values as environment variables when you execute the script.

Last updated

Logo