Securing Your Foldspace AI Agent with JWT Authentication
Foldspace now supports JWT-based authentication for AI agents. This feature enables you to securely protect user identity, conversation history, and agent actions by ensuring that only authenticated users can access their own AI sessions. This article explains why JWT authentication matters, how it works in Foldspace, and how to implement it safely in your backend and web application.
Why This Matters
Without authentication, a malicious actor could impersonate a user, access private conversations, or invoke actions on their behalf. As AI agents become more deeply integrated into product workflows, identity security becomes critical.
JWT authentication ensures:
- A user can only access their own conversations and data
- Requests to the AI agent cannot be forged from the client side
- Conversation history and agent actions are protected from identity theft
Background: What Is a JWT?
A JSON Web Token (JWT) is a compact, signed token commonly used to securely transmit identity information between systems.
A JWT:
- Is generated by a trusted backend
- Is cryptographically signed using a secret key
- Can be verified by a server without additional database lookups
- Has a built-in expiration time
In Foldspace, the JWT acts as a proof of identity for the user interacting with the AI agent.
The Problem JWT Solves: Identity Theft
Without a signed token:
- Any client could claim to be any user
- User IDs passed from the browser could be tampered with
- Chat history and AI actions could be accessed by unauthorized parties
By requiring a server-signed JWT, Foldspace ensures:
- User identity cannot be spoofed
- Only authenticated users can send messages or retrieve conversations
- Tokens automatically expire, limiting exposure if compromised
How JWT Authentication Works in Foldspace
At a high level:
- You generate a secret key in the Foldspace dashboard
- Your backend uses this secret to sign a JWT using HS256
- The signed JWT is sent to the browser
- The Foldspace Web SDK includes the JWT in every request
- Foldspace verifies the token and user identity on every call
Step 1: Generate a Secret Key in Foldspace
JWT signing keys are managed in the Foldspace under:
Settings → Identity Verification
You can generate one or more JWT secret keys.
- These keys are used to sign JWTs in your backend
- They must be kept private and secure
- They must never be exposed in frontend code
Access Control
To copy a secret key or change a key’s status, the Foldspace user must have the Jwt Settings Admin role.
Users without this role can view configuration but cannot access or modify secret keys.
Once generated, copy the secret key and store it securely (for example, as an environment variable).
Key Rotation and Secret Key Management
Foldspace supports key rotation to help you maintain strong security practices without service disruption. Key rotation is fully managed by you and allows multiple secret keys to coexist, enabling safe transitions between keys in production.
Each secret key has a status that controls how it is enforced.
Secret Key Statuses
INACTIVE
- Default status when a key is created
- JWT verification is not enforced
- The key can be copied and safely prepared for deployment
- Can be moved to INACTIVE from any status except REVOKED
ACTIVE
- JWT verification is fully enforced
- Tokens signed with this key are accepted by Foldspace
TESTING
- Used to validate JWT signing without enforcing authentication
- Only one TESTING key is allowed at a time
- JWT verification results are returned in a response header
- Does not affect production traffic or agent availability
DEPRECATED
- Used during key rotation
- The key remains valid and enforced
- Allows existing backend deployments to continue working while a new key is rolled out
REVOKED
- Permanently disabled and deleted
- Tokens signed with this key are rejected
- Status cannot be changed once revoked
Recommended Key Rotation Flow
- Create a new secret key (initially INACTIVE)
- Deploy the new key to your backend
- Move the new key to ACTIVE
- Move the old key to DEPRECATED
- Once fully migrated, move the deprecated key to REVOKED
This allows safe key rotation with no downtime.
Step 2: Sign the JWT in Your Backend
The JWT must be created only in your backend and must be signed using the HS256 algorithm.
Required JWT Payload
{
"userId": "<the same user ID you pass to the Foldspace JS SDK>",
"exp": <expiration time in seconds since epoch>
}Signing Requirements
- Algorithm:
HS256 - Secret: ACTIVE or DEPRECATED Foldspace secret key
- Location: Backend only
Tokens signed with any other algorithm are rejected.
Backend Code Examples
Node.js (jsonwebtoken)
import jwt from "jsonwebtoken";
const FOLDSPACE_SECRET = process.env.FOLDSPACE_JWT_SECRET;
function generateFoldspaceToken(userId) {
const expiresInSeconds =
Math.floor(Date.now() / 1000) + (15 * 60);
return jwt.sign(
{ userId, exp: expiresInSeconds },
FOLDSPACE_SECRET,
{ algorithm: "HS256" }
);
}Python (PyJWT)
import jwt
import time
import os
FOLDSPACE_SECRET = os.environ["FOLDSPACE_JWT_SECRET"]
def generate_foldspace_token(user_id):
payload = {
"userId": user_id,
"exp": int(time.time()) + 900
}
return jwt.encode(
payload,
FOLDSPACE_SECRET,
algorithm="HS256"
)Ruby (jwt gem)
require 'jwt'
secret = ENV['FOLDSPACE_JWT_SECRET']
def generate_foldspace_token(user_id, secret)
payload = {
userId: user_id,
exp: Time.now.to_i + 900
}
JWT.encode(payload, secret, 'HS256')
endStep 3: Passing the JWT to the Foldspace Web SDK
The signed JWT must be provided to the Foldspace Web SDK via the agent API.
JavaScript SDK Example
// 1. Fetch the token from your backend API
const response = await fetch('/api/auth/foldspace-token');
const { token } = await response.json();
// 2. Initialize Foldspace agent via the agent API
const agent = foldspace.agent({
apiName: 'the-agent-api-name',
token: token,
onTokenExpired: async () => {
const response = await fetch('/api/auth/foldspace-token');
const { token } = await response.json();
console.log('token refreshed', token);
return token;
}
});
agent.show();How This Works
- The frontend fetches a signed JWT from your backend
- The token is passed using the
tokenproperty - The SDK automatically attaches the token to every request
- When the token expires,
onTokenExpiredis triggered - Your UI fetches and returns a new token
Testing Your Signed JWT
Foldspace provides a TESTING key status to help you validate JWT signing before enforcing authentication in production.
How Testing Works
- Move a secret key to TESTING
- Only one key can be in TESTING at a time
- Sign a JWT using the TESTING key
- Send requests using this JWT via the Foldspace SDK
- Foldspace evaluates the token and returns the result in a response header
Response Header
For requests signed with a TESTING key, Foldspace evaluates the JWT and returns the result in a response header:
X-Jwt-Testing-ResultPossible values:
validated— the JWT is correctly signed and structuredfailed— the JWT is invalid, expired, or incorrectly signed
This allows you to safely verify:
- Signature correctness
- Payload structure
- Expiration handling
…without impacting production users.
Important Notes
- JWTs signed with ACTIVE or DEPRECATED keys are enforced and must be valid
- JWTs signed with a TESTING key are evaluated but not enforced
- When a TESTING key is used, the request proceeds and the verification result is surfaced only via the response header
- This behavior allows production-safe validation before key rotation
When to Use TESTING
Use a TESTING key when you want to:
- Validate a new backend JWT implementation
- Confirm correct signing algorithm (
HS256) - Verify payload structure and expiration handling
- Test new keys before promoting them to ACTIVE
Choosing a Secure Expiration Time
Best practices:
- Use short-lived tokens (5–30 minutes)
- Refresh tokens from your backend when needed
Short expiration times reduce risk and align with modern security standards.
Error Handling and Token Lifecycle
Token Expired
onTokenExpiredis invoked by the SDK- Fetch a new JWT with a fresh
expfrom your backend - Return the new token to the SDK
Invalid Token
If the token is invalid or cannot be verified:
- All agent requests are rejected
- The agent is automatically hidden from the UI
- User data and actions remain protected
Summary
JWT authentication secures your Foldspace AI agent by:
- Preventing identity spoofing
- Protecting conversations and actions
- Enforcing backend-verified identity
- Requiring HS256-signed tokens
- Supporting seamless token refresh
- Enabling safe key rotation without downtime
JWT authentication is strongly recommended for all production deployments of Foldspace agents.
Updated about 2 months ago