Authentication
JWT-based authentication system for the SUDIGITAL API with role-based access control.
Overview
The SUDIGITAL API uses JWT (JSON Web Tokens) for authentication with comprehensive role-based permissions for crypto trading operations.
Security Features
- JWT Authentication: Secure token-based access control
- Role-Based Permissions: 7 user roles with granular trading permissions
- Rate Limiting: Multi-tier rate limiting to prevent abuse
- Encrypted Storage: AES-256-CBC encryption for sensitive data
- Resource Ownership: Users can only access their own trading resources
User Roles & Permissions
| Role | Trading | API Keys | Bots | Admin Operations |
|---|---|---|---|---|
| Super Admin | ✅ | ✅ | ✅ | ✅ |
| Admin | ✅ | ✅ | ✅ | ✅ |
| Moderator | ✅ | ✅ | ✅ | ❌ |
| Owner | ✅ | ✅ | ✅ | ❌ |
| Worker | ✅ | ✅ | ✅ | ❌ |
| Player | ✅ | ✅ | ❌ | ❌ |
| User | ✅ | ✅ | ❌ | ❌ |
Authentication Methods
1. JWT (JSON Web Tokens)
JWT tokens are the primary authentication method for user sessions.
Login Endpoint
http
POST /api/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "your-password"
}Response
json
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_in": 3600,
"token_type": "Bearer"
}Using JWT Tokens
http
GET /api/users/me
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...Rate Limiting
Different endpoints have different rate limits to ensure fair usage:
Trading Endpoints
- Limit: 100 requests per 15 minutes per user
- Applies to: All
/api/users/:id/bots,/api/users/:id/transactionsendpoints - Headers:
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset
Exchange Key Management
- Limit: 10 requests per hour per user
- Applies to: All
/api/users/:id/exchange-keysendpoints - Purpose: Prevents abuse of sensitive credential operations
General API
- Limit: 200 requests per 15 minutes per user/IP
- Applies to: Most other API endpoints
- Tracking: By authenticated user ID or IP address
Rate Limit Response
When rate limit is exceeded:
json
{
"success": false,
"error": "Rate limit exceeded. Please wait before making more requests.",
"retryAfter": 300
}Security Implementation
Data Encryption
- Exchange API Keys: Encrypted with AES-256-CBC before database storage
- Sensitive Fields: Masked in API responses for security
- Environment Keys: Secure key management with environment variables
Authentication Middleware
- Trading Auth: Enhanced authentication for trading operations
- Permission Checks: Granular permission validation per endpoint
- Ownership Verification: Users can only access their own resources
2. API Keys
API keys will be available for service-to-service authentication.
Creating API Keys
http
POST /api/auth/api-keys
Authorization: Bearer your-jwt-token
Content-Type: application/json
{
"name": "My Service API Key",
"permissions": ["users:read", "users:write"],
"expires_at": "2025-12-31T23:59:59.000Z"
}Using API Keys
http
GET /api/users
X-API-Key: sk_live_1234567890abcdef3. OAuth 2.0
OAuth 2.0 support will be available for third-party integrations.
Supported Flows
- Authorization Code - For web applications
- Client Credentials - For server-to-server communication
- Device Code - For CLI and IoT applications
User Registration
Create Account
http
POST /api/auth/register
Content-Type: application/json
{
"email": "user@example.com",
"password": "SecurePassword123!",
"firstName": "John",
"lastName": "Doe"
}Email Verification
http
POST /api/auth/verify-email
Content-Type: application/json
{
"token": "email-verification-token"
}Password Management
Reset Password Request
http
POST /api/auth/forgot-password
Content-Type: application/json
{
"email": "user@example.com"
}Reset Password
http
POST /api/auth/reset-password
Content-Type: application/json
{
"token": "reset-password-token",
"password": "NewSecurePassword123!"
}Change Password
http
PUT /api/auth/change-password
Authorization: Bearer your-jwt-token
Content-Type: application/json
{
"current_password": "CurrentPassword123!",
"new_password": "NewSecurePassword123!"
}Token Management
Refresh Tokens
http
POST /api/auth/refresh
Content-Type: application/json
{
"refresh_token": "your-refresh-token"
}Logout
http
POST /api/auth/logout
Authorization: Bearer your-jwt-tokenLogout All Sessions
http
POST /api/auth/logout-all
Authorization: Bearer your-jwt-tokenSession Management
Get Current Session
http
GET /api/auth/session
Authorization: Bearer your-jwt-tokenList All Sessions
http
GET /api/auth/sessions
Authorization: Bearer your-jwt-tokenRevoke Session
http
DELETE /api/auth/sessions/{session_id}
Authorization: Bearer your-jwt-tokenPermissions & Scopes
Available Scopes
users:read- Read user informationusers:write- Create and update usersusers:delete- Delete usersadmin:read- Read admin informationadmin:write- Admin operations
Permission Checking
http
GET /api/auth/permissions
Authorization: Bearer your-jwt-tokenSecurity Features
Multi-Factor Authentication (MFA)
Enable MFA
http
POST /api/auth/mfa/enable
Authorization: Bearer your-jwt-token
Content-Type: application/json
{
"method": "totp"
}Verify MFA Setup
http
POST /api/auth/mfa/verify-setup
Authorization: Bearer your-jwt-token
Content-Type: application/json
{
"code": "123456"
}MFA Login
http
POST /api/auth/mfa/verify
Content-Type: application/json
{
"mfa_token": "temporary-mfa-token",
"code": "123456"
}Rate Limiting
Authentication endpoints will have specific rate limits:
- Login attempts: 5 per minute per IP
- Password reset: 3 per hour per email
- Registration: 10 per hour per IP
Error Responses
Authentication Errors
Invalid Credentials
json
{
"error": {
"code": "INVALID_CREDENTIALS",
"message": "Invalid email or password"
},
"status": 401
}Token Expired
json
{
"error": {
"code": "TOKEN_EXPIRED",
"message": "Access token has expired"
},
"status": 401
}Insufficient Permissions
json
{
"error": {
"code": "INSUFFICIENT_PERMISSIONS",
"message": "You don't have permission to access this resource",
"required_scope": "users:write"
},
"status": 403
}Implementation Timeline
Phase 1: Basic Authentication (Week 1)
- ✅ User registration
- ✅ Email/password login
- ✅ JWT token generation
- ✅ Password reset
Phase 2: Enhanced Security (Week 2)
- 🔄 MFA support (TOTP)
- 🔄 Session management
- 🔄 Rate limiting
- 🔄 Audit logging
Phase 3: Advanced Features (Week 3)
- 🔄 API key management
- 🔄 OAuth 2.0 support
- 🔄 Fine-grained permissions
- 🔄 SSO integration
Configuration
Environment Variables
properties
# JWT Configuration
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=1h
JWT_REFRESH_EXPIRES_IN=7d
# Password Policy
PASSWORD_MIN_LENGTH=8
PASSWORD_REQUIRE_UPPERCASE=true
PASSWORD_REQUIRE_NUMBERS=true
PASSWORD_REQUIRE_SYMBOLS=true
# MFA Configuration
MFA_ISSUER=SUDIGITAL
MFA_SERVICE_NAME=SUDIGITAL API
# Rate Limiting
RATE_LIMIT_LOGIN=5
RATE_LIMIT_WINDOW=60000SDKs and Examples
JavaScript/TypeScript
typescript
import { SUDIGITALClient } from '@sudigital/client'
const client = new SUDIGITALClient({
baseURL: 'http://localhost:3001',
apiKey: 'your-api-key',
})
// Login
const { access_token } = await client.auth.login({
email: 'user@example.com',
password: 'password',
})
// Use authenticated client
client.setToken(access_token)
const user = await client.users.me()Python
python
from sudigital import Client
client = Client(base_url='http://localhost:3001')
# Login
token_response = client.auth.login(
email='user@example.com',
password='password'
)
# Use authenticated client
client.set_token(token_response.access_token)
user = client.users.me()cURL Examples
bash
# Login
curl -X POST http://localhost:3001/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "password"
}'
# Use token
curl -X GET http://localhost:3001/api/users/me \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."Testing Authentication
Development Tools
- Postman Collection - Import our collection for easy testing
- Insomnia - REST client with environment support
- Thunder Client - VS Code extension for API testing
Test Accounts
Development environment will include test accounts:
admin@sudigital.com/admin123(Admin user)user@sudigital.com/user123(Regular user)viewer@sudigital.com/viewer123(Read-only user)
Troubleshooting
Common Issues
Token not working
- Check token expiration
- Verify Bearer prefix in Authorization header
- Ensure token is properly formatted
Login fails
- Verify email and password
- Check for account lockout
- Ensure account is verified
Permission denied
- Check required scopes
- Verify user role
- Ensure token has sufficient permissions
Debug Headers
Include these headers for debugging:
http
X-Debug: true
X-Request-ID: unique-request-idRelated Resources
- Users API - User management endpoints
- API Overview - General API information
- Quick Start - Get started guide