JWT Tokens

JSON Web Tokens (JWT) provide a secure method for transmitting information between parties as a JSON object.

JWT Structure

A JWT consists of three parts separated by dots:

header.payload.signature
{
"alg": "HS256",
"typ": "JWT"
}

Payload

{
"sub": "1234567890",
"email": "[email protected]",
"iat": 1516239022,
"exp": 1516242622
}

Signature

The signature is created using:

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

Creating JWT Tokens

Node.js Example

const jwt = require('jsonwebtoken');
const payload = {
userId: '12345',
scope: ['email', 'contacts']
};
const token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: '1h',
issuer: 'your-app',
audience: 'brevo-api'
});

Python Example

import jwt
import datetime
payload = {
'user_id': '12345',
'email': '[email protected]',
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1),
'iat': datetime.datetime.utcnow()
}
token = jwt.encode(payload, 'your-secret-key', algorithm='HS256')

Using JWT with Brevo API

Terminal window
curl -X GET "https://api.brevo.com/v3/account" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
-H "Accept: application/json"

Token Validation

const validateToken = (token) => {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
return { valid: true, payload: decoded };
} catch (error) {
return { valid: false, error: error.message };
}
};

Best Practices

  • Use strong, random secrets
  • Set appropriate expiration times
  • Validate tokens on every request
  • Use HTTPS only
  • Store secrets securely
  • Implement token refresh logic