3. Rotating API tokens
API Token Rotation Overview
API token rotation is a security best practice that involves periodically replacing existing tokens with new ones to minimize the risk of compromised credentials. This scenario demonstrates a complete token rotation workflow that can be performed without service interruption.
Key benefits of token rotation:
Reduces the impact of potentially leaked or compromised tokens
Enforces time-limited access even for long-lived integrations
Helps maintain compliance with security policies and regulations
Can be performed without downtime for your integrations
Token rotation should be performed as part of a regular security maintenance schedule. The frequency depends on your security requirements - monthly, quarterly, or annually are common intervals.
This scenario assumes you already have an active API token that will be rotated. See our other scenario to learn how to generate your first API token.
Step 1 - List active API tokens to identify rotation candidates (Optional)
Retrieves a list of all active API tokens for your account. This optional step helps you identify tokens that need rotation based on age or usage patterns.
Identify tokens that are approaching your organization's maximum age policy
Note token IDs and descriptions to ensure you're rotating the correct tokens
Check creation dates to prioritize rotation of older tokens first
Review last usage timestamps to identify potentially unused or stale tokens
This endpoint is called using your existing API token - the same one you'll be rotating in the subsequent steps.
Endpoint
GET /api/key
Request
GET /api/key?token=ftS1MQyvmoM4suOTDeqnJA0PidHVX169xXkmLJ3VlRvLvraecachyHyLLpAIwCRo
Response
{
"results": [
{
"id": "ftS1MQyvmoM4suOTDeqnJA0PidHVX169xXkmLJ3VlRvLvraecachyHyLLpAIwCRo",
"description": "Initial integration token",
"created": "2022-06-21T15:30:45Z",
"lastUsed": "2023-06-20T14:22:10Z",
"apiKeyType": "generic"
}
]
}
The response contains an array of all active API tokens for your account.
Before proceeding with rotation, ensure you have a plan to update all systems using the token. There will be a brief period where both tokens are valid to allow for a smooth transition.
Step 2 - Generate a new replacement API token
Creates a new API token that will replace your existing one. This is the first active step in the rotation process and requires no additional authentication beyond your current token.
The new token will have the same permissions as the user who owns the existing token
Include a descriptive name in the "description" field to track the token's purpose
The new token will be valid for 10 years by default, but can be rotated again at any time
It's important to create the new token before revoking the old one to ensure continuous service availability during the transition. This approach allows you to perform the complete rotation using only your existing API token.
Endpoint
POST /api/key
Request
POST /api/key?token=ftS1MQyvmoM4suOTDeqnJA0PidHVX169xXkmLJ3VlRvLvraecachyHyLLpAIwCRo
Content-Type: application/json
{
"description": "Rotated API token"
}
Response
{
"id": "5PyJauwDC56elwfawK3HtW6pIYl0tAGG8hTK26jbGGcXHJCQVmuKmszyzISHKUCy"
}
The response contains the following important properties:
newApiToken - Located at
id
in the response.The unique identifier for the newly created API token that will replace your existing token. This new token has the same permissions as the user who owns the existing token and is valid for 10 years.
Example value:
5PyJauwDC56elwfawK3HtW6pIYl0tAGG8hTK26jbGGcXHJCQVmuKmszyzISHKUCy
The new replacement API token has been successfully created and can now be deployed to your integration systems.
Next steps:
Update your integration systems with the new token before deactivating the old one
Allow for a transition period where both tokens are valid
Monitor your systems to confirm they're successfully using the new token
Once confirmed, proceed to revoke the old token
Store this new token securely using environment variables, secrets management systems, or secure vaults - never in source code repositories.
Step 3 - Revoke the old API token to complete the rotation process
Permanently invalidates the old API token after confirming that all integrations are successfully using the new token. This completes the rotation process.
Only revoke the old token after confirming all systems are using the new token
This action cannot be undone - the old token will immediately stop working
Consider implementing monitoring to detect any authentication failures after revocation
This action finalizes the token rotation process. Any systems still using the old token will lose access immediately.
Endpoint
DELETE /api/key/:token
Request
DELETE /api/key/ftS1MQyvmoM4suOTDeqnJA0PidHVX169xXkmLJ3VlRvLvraecachyHyLLpAIwCRo
The old API token has been successfully revoked, completing the rotation process.
In a real-world scenario, you would typically wait a period of time (hours or days) between creating the new token and revoking the old one to ensure all systems have been updated.
API Token Rotation Best Practices
Implementing a regular token rotation schedule is an essential security practice:
Establish a consistent rotation schedule based on your security requirements
Automate the rotation process where possible to minimize human error
Maintain a transition period where both old and new tokens are valid
Consider using shorter rotation intervals for tokens with higher privileges
Example Token Rotation Implementation
See our OpenAPI documentation to learn about the full set of API endpoints and parameters.
Please use proper exception handling and function decomposition in your own code. The code is provided for illustrative purposes only and is not intended for production use.
// Complete token rotation workflow
const URL = "https://sandbox.circularo.com";
const API_PATH = "/api/v1";
// This scenario assumes you already have an active API token, that will be rotated.
const apiToken = "YOUR_EXISTING_API_TOKEN";
try {
// Step 1: List all active API tokens to check age (optional)
const listTokensResponse = await fetch(`${URL}${API_PATH}/api/key?token=${apiToken}`);
if (!listTokensResponse.ok) {
throw new Error(`API Token fetch failed: ${listTokensResponse.status} ${listTokensResponse.statusText}`);
}
const { results: apiTokens } = await listTokensResponse.json();
// Find our token to check its age
const tokenToRotate = apiTokens.find((token) => (token.id === apiToken));
if (!tokenToRotate) {
throw new Error('Token to rotate not found');
}
const tokenCreationDate = new Date(tokenToRotate.created);
const tokenAgeInDays = Math.floor((new Date() - tokenCreationDate) / (1000 * 60 * 60 * 24));
console.log(`Token age: ${tokenAgeInDays} days`);
// Step 2: Create a new replacement token
const newTokenResponse = await fetch(`${URL}${API_PATH}/api/key?token=${apiToken}`, {
method: 'POST',
body: JSON.stringify({
description: "Rotated token"
}),
headers: { 'Content-Type': 'application/json' }
});
if (!newTokenResponse.ok) {
throw new Error(`Token creation failed: ${newTokenResponse.status} ${newTokenResponse.statusText}`);
}
const { id: newApiToken } = await newTokenResponse.json();
console.log("New API token created");
// Step 3: Update your systems to use the new token
// 1. Update configuration in all systems using the token
// 2. Verify systems are working with the new token
// 3. Wait for a transition period (hours or days)
// Step 4: Revoke the old token after transition period
await fetch(`${URL}${API_PATH}/api/key/${apiToken}`, {
method: 'DELETE'
});
console.log("Old API token successfully revoked");
} catch (error) {
console.error('Error in API Token rotation flow:', error.message);
}
Automating Token Rotation
Regular token rotation significantly reduces the security risks associated with long-lived credentials while maintaining the convenience of API token authentication for your integrations.