🔐 Authentication
JWT Authentication

Authentication with JWT

This guide explains how to authenticate with our gamification API using JSON Web Tokens (JWT).

What is JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

How JWT Authentication Works

  1. Your application generates a JWT containing user identity claims
  2. The JWT is sent in the Authorization header with API requests
  3. Our API validates the token signature and claims
  4. If valid, the request is processed; if invalid, authentication fails

Implementing JWT Authentication

Step 1: Generate a JWT

Create a JWT with the required claims signed with your API secret:

const jwt = require("jsonwebtoken");
 
// Your API Secret (keep this secure!)
const API_SECRET = "your-api-secret";
 
// Create the JWT
const token = jwt.sign(
  {
    // Standard claims
    sub: "user_123", // Subject (user ID)
    iss: "your-tenant-id", // Issuer (your tenant)
    aud: "your-application-id", // Audience (your project)
    iat: Math.floor(Date.now() / 1000), // Issued at (current time)
    exp: Math.floor(Date.now() / 1000) + 60 * 60, // Expiration (1 hour)
    // Custom claims for gamification
    scope: ["read", "write"],
  },
  API_SECRET
);

Step 2: Include the JWT in API Requests

Add the JWT to the Authorization header of your HTTP requests:

curl -X POST https://api.example.com/v1/events \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{ ... }'

Warning

Losing or compromising your secret can disrupt your API access. To regain access, refresh your secret by visiting:

Refresh your secret

Required Claims

The following claims are required in your JWT:

ClaimDescriptionRequired
subSubject identifier. This should be the user's unique ID in your system.Yes
issIssuer. This should be your tenant ID registered with our system.Yes
audAudience. This should be your application ID registered with our system.Yes
iatIssued At. Timestamp when the token was generated (in seconds since Unix epoch).Yes
expExpiration Time. Timestamp when the token expires (in seconds since Unix epoch).Yes
scopeArray of permission strings that define what actions the token can perform.No

JWT Format Example

A decoded JWT contains three parts:

Header:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload:

{
  "sub": "user_123",
  "iss": "your-tenant-id",
  "aud": "your-application-id",
  "iat": 1696134000,
  "exp": 1696137600,
  "scope": ["read", "write"]
}

Signature:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  API_SECRET
)

Common Authentication Errors

Error CodeDescriptionSolution
invalid_tokenJWT is malformed or cannot be parsedCheck the token format and ensure it's properly encoded
token_expiredThe JWT has expiredGenerate a new token with a future expiration time
invalid_signatureThe JWT signature verification failedEnsure you're using the correct API secret for signing
missing_required_claimA required claim is missing from the JWTAdd the missing claim to your token generation logic
insufficient_permissionsThe token lacks necessary permissionsUpdate the permissions claim in your token

Security Best Practices

  1. Store Your API Secret Securely: Never expose your API secret in client-side code.

  2. Short Expiration Times: Set short expiration times for your tokens (typically 1-24 hours).

  3. Use HTTPS: Always use HTTPS when transmitting JWTs.

  4. Minimize Claims: Only include necessary claims to reduce token size.

  5. Token Revocation Strategy: Implement a strategy for revoking tokens if needed.

  6. Regular Secret Rotation: Rotate your API secrets periodically.

Verifying JWT Setup

To verify your JWT implementation is correct, you can use our test endpoint:

GET https://api.example.com/v1/auth/verify

This endpoint will validate your JWT and return information about the authenticated entity.

Next Steps

Now that you understand JWT authentication for our API, you might want to:

For more information, check our API Reference or contact support.