---
title: "JWT Tokens | Tajo"
description: "JSON Web Tokens for secure API authentication"
url: https://tajo.io/docs/authentication/jwt-tokens/
markdown: https://tajo.io/docs/authentication/jwt-tokens.md
lang: en-US
author: "Set Noa"
author_url: https://tajo.io/set-noa/
---

# JWT Tokens

[Set Noa](https://tajo.io/set-noa/)

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
```

### Header

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

### Payload

```json
{
  "sub": "1234567890",
  "email": "user@example.com",
  "iat": 1516239022,
  "exp": 1516242622
}
```

### Signature

The signature is created using:

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

## Creating JWT Tokens

### Node.js Example

```javascript
const jwt = require('jsonwebtoken');

const payload = {
  userId: '12345',
  email: 'user@example.com',
  scope: ['email', 'contacts']
};

const token = jwt.sign(payload, process.env.JWT_SECRET, {
  expiresIn: '1h',
  issuer: 'your-app',
  audience: 'brevo-api'
});
```

### Python Example

```python
import jwt
import datetime

payload = {
    'user_id': '12345',
    'email': 'user@example.com',
    '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

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

## Token Validation

```javascript
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
