Generating API tokens
- In order to access the endpoints of SecretVault/SecretDataAnalytics, you will require a set of Bearer tokens for authorization - one for each node in your setup.
- Those can be generated programmatically using the information from your
Credentials
andCluster Config
. - Specifically you'll be able to generate them with just the following information using the code below:
- Your private key
- Your DID
- The target node's DID
- We're encouraging generation during runtime with short TTL for these tokens, but it's up to you if you want to manually rotate them on longer intervals.
- Python
- JavaScript (from scratch)
- JavaScript (with wrapper)
- Python (with wrapper)
# generate.py
# pip install "PyJWT[crypto]" ecdsa
import jwt
import time
from ecdsa import SigningKey, SECP256k1
def create_jwt(secret_key: str = None,
org_did: str = None,
node_ids: list = None,
ttl: int = 3600) -> list:
"""
Create JWTs signed with ES256K for multiple node_ids
"""
# Convert the secret key from hex to bytes
private_key = bytes.fromhex(secret_key)
signer = SigningKey.from_string(private_key, curve=SECP256k1)
tokens = []
for node_id in node_ids:
# Create payload for each node_id
payload = {
"iss": org_did,
"aud": node_id,
"exp": int(time.time()) + ttl
}
# Create and sign the JWT
token = jwt.encode(
payload,
signer.to_pem(),
algorithm="ES256K"
)
tokens.append(token)
print(f"Generated JWT for {node_id}: {token}")
return tokens
# # Replace secret_key with secret Key
# # Replace org_did with DID for organization
# # Replace node_ids with the Node DIDs
if __name__ == "__main__":
secret_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
org_did = "did:nil:testnet:nillionXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
# these are the demo cluster node dids, change them if your config is different
node_ids = [
"did:nil:testnet:nillion1fnhettvcrsfu8zkd5zms4d820l0ct226c3zy8u",
"did:nil:testnet:nillion14x47xx85de0rg9dqunsdxg8jh82nvkax3jrl5g",
"did:nil:testnet:nillion167pglv9k7m4gj05rwj520a46tulkff332vlpjp"
]
create_jwt(secret_key, org_did, node_ids)
nildb/secretvault_nextjs_niql/generate.js
404: Not Found
Install secretvaults
npm i secretvaults
Run the generateApiTokens script
node generateApiTokens.js
- generateApiTokens.js
- orgConfig.js
examples/generateApiTokens.js
import { SecretVaultWrapper } from "secretvaults";
import { orgConfig } from "./orgConfig.js";
async function main() {
try {
const org = new SecretVaultWrapper(
orgConfig.nodes,
orgConfig.orgCredentials,
);
await org.init();
// generate api tokens for all nodes in the org config
const apiTokens = await org.generateTokensForAllNodes();
console.log("🪙 API Tokens:", apiTokens);
} catch (error) {
console.error("❌ Failed to use SecretVaultWrapper:", error.message);
process.exit(1);
}
}
main();
examples/orgConfig.js
import dotenv from "dotenv";
dotenv.config();
export const orgConfig = {
orgCredentials: {
secretKey: process.env.NILLION_ORG_SECRET_KEY,
orgDid: process.env.NILLION_ORG_DID,
},
nodes: [
{
url: "https://nildb-nx8v.nillion.network",
did: "did:nil:testnet:nillion1qfrl8nje3nvwh6cryj63mz2y6gsdptvn07nx8v",
},
{
url: "https://nildb-p3mx.nillion.network",
did: "did:nil:testnet:nillion1uak7fgsp69kzfhdd6lfqv69fnzh3lprg2mp3mx",
},
{
url: "https://nildb-rugk.nillion.network",
did: "did:nil:testnet:nillion1kfremrp2mryxrynx66etjl8s7wazxc3rssrugk",
},
],
};
Install secretvaults
pip install secretvaults
Run the generate_api_tokens script
python3 generate_api_tokens.py
- generate_api_tokens.py
- org_config.py
examples/generate_api_tokens.py
"""Generating API tokens example using the SecretVault wrapper"""
import asyncio
import json
import sys
from secretvaults import SecretVaultWrapper
from org_config import org_config
async def main():
"""
Main function to print the org config, initialize the SecretVaultWrapper,
and generate API tokens for all nodes.
"""
try:
# Initialize the SecretVaultWrapper instance with the org configuration
org = SecretVaultWrapper(org_config["nodes"], org_config["org_credentials"])
await org.init()
# Generate API tokens for all nodes
api_tokens = await org.generate_tokens_for_all_nodes()
print("🪙 API Tokens:", json.dumps(api_tokens, indent=2))
except RuntimeError as error:
print(f"❌ Failed to use SecretVaultWrapper: {str(error)}")
sys.exit(1)
# Run the async main function
if __name__ == "__main__":
asyncio.run(main())
examples/org_config.py
"""The SecretVault organization configuration"""
import os
from dotenv import load_dotenv
load_dotenv()
# Organization configuration
org_config = {
"org_credentials": {
"secret_key": os.getenv("NILLION_ORG_SECRET_KEY"),
"org_did": os.getenv("NILLION_ORG_DID"),
},
"nodes": [
{
"url": "https://nildb-nx8v.nillion.network",
"did": "did:nil:testnet:nillion1qfrl8nje3nvwh6cryj63mz2y6gsdptvn07nx8v",
},
{
"url": "https://nildb-p3mx.nillion.network",
"did": "did:nil:testnet:nillion1uak7fgsp69kzfhdd6lfqv69fnzh3lprg2mp3mx",
},
{
"url": "https://nildb-rugk.nillion.network",
"did": "did:nil:testnet:nillion1kfremrp2mryxrynx66etjl8s7wazxc3rssrugk",
},
],
}