Authentication API
Complete reference for user authentication, session management, and token handling in MegaVault.
Table of Contents
Authentication Overview
MegaVault uses JWT-based authentication with secure session management. The authentication system supports both web and mobile applications.
JWT Tokens
Secure token-based auth
- ✅ Stateless authentication
- ✅ Configurable expiration
- ✅ Secure token signing
- ✅ Auto-refresh capability
Session Management
Persistent sessions
- ✅ Redis-based storage
- ✅ Cross-device sessions
- ✅ Session invalidation
- ✅ Security monitoring
Security Features
Enterprise-grade security
- ✅ Password hashing (bcrypt)
- ✅ Rate limiting
- ✅ CSRF protection
- ✅ Secure cookies
💡
Base URL
All authentication endpoints are prefixed with:
/api/authSign In
Authenticate a user with email and password to receive an access token.
Request
POST /api/auth/signin
Content-Type: application/json
{
"email": "user@example.com",
"password": "securepassword123"
}Response
Success Response (200)
{
"success": true,
"user": {
"id": "user_123456789",
"email": "user@example.com",
"name": "John Doe",
"avatar": "https://example.com/avatar.jpg",
"createdAt": "2024-01-15T10:30:00Z",
"lastLoginAt": "2024-01-20T14:25:00Z"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": "24h",
"refreshToken": "rt_abc123def456..."
}Error Response (401)
{
"success": false,
"error": {
"code": "INVALID_CREDENTIALS",
"message": "Invalid email or password",
"field": "credentials"
}
}Validation Rules
- email: Valid email format, required
- password: Minimum 8 characters, required
Sign Up
Register a new user account with email, password, and optional profile information.
Request
POST /api/auth/signup
Content-Type: application/json
{
"email": "newuser@example.com",
"password": "securepassword123",
"name": "Jane Smith",
"confirmPassword": "securepassword123"
}Response
Success Response (201)
{
"success": true,
"user": {
"id": "user_987654321",
"email": "newuser@example.com",
"name": "Jane Smith",
"avatar": null,
"createdAt": "2024-01-20T15:45:00Z",
"emailVerified": false
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"message": "Account created successfully. Please check your email for verification."
}Error Response (400)
{
"success": false,
"error": {
"code": "EMAIL_ALREADY_EXISTS",
"message": "An account with this email already exists",
"field": "email"
}
}Validation Rules
- email: Valid email format, unique, required
- password: Minimum 8 characters, required
- confirmPassword: Must match password, required
- name: 2-50 characters, optional
Sign Out
Invalidate the current session and sign out the user.
Request
POST /api/auth/signout
Authorization: Bearer YOUR_JWT_TOKENResponse
Success Response (200)
{
"success": true,
"message": "Successfully signed out"
}Session Management
Retrieve current session information and verify token validity.
Get Current Session
Request
GET /api/auth/session
Authorization: Bearer YOUR_JWT_TOKENSuccess Response (200)
{
"success": true,
"user": {
"id": "user_123456789",
"email": "user@example.com",
"name": "John Doe",
"avatar": "https://example.com/avatar.jpg"
},
"session": {
"id": "session_abc123",
"createdAt": "2024-01-20T10:00:00Z",
"expiresAt": "2024-01-21T10:00:00Z",
"ipAddress": "192.168.1.1",
"userAgent": "Mozilla/5.0..."
}
}Refresh Token
Request
POST /api/auth/refresh
Content-Type: application/json
{
"refreshToken": "rt_abc123def456..."
}Success Response (200)
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": "24h",
"refreshToken": "rt_new123token456..."
}JWT Tokens
Understanding JWT token structure and usage in MegaVault API.
Token Structure
JWT Payload
{
"sub": "user_123456789",
"email": "user@example.com",
"name": "John Doe",
"iat": 1640995200,
"exp": 1641081600,
"scope": ["read", "write"]
}Token Usage
- Header Format:
Authorization: Bearer TOKEN - Expiration: Tokens expire after 24 hours by default
- Refresh: Use refresh token to get new access token
- Storage: Store securely (localStorage for web, Keychain for mobile)
Security Best Practices
- HTTPS Only: Always use HTTPS in production
- Secure Storage: Store tokens securely on client side
- Short Expiration: Keep access token expiration short
- Rotate Refresh Tokens: Refresh tokens should be rotated
Code Examples
Implementation examples for common authentication flows.
JavaScript/Node.js
Authentication Service
class AuthService {
constructor(baseURL) {
this.baseURL = baseURL;
this.token = localStorage.getItem('authToken');
}
async signIn(email, password) {
const response = await fetch(`${this.baseURL}/api/auth/signin`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (data.success) {
this.token = data.token;
localStorage.setItem('authToken', data.token);
localStorage.setItem('refreshToken', data.refreshToken);
return data.user;
} else {
throw new Error(data.error.message);
}
}
async signOut() {
if (this.token) {
await fetch(`${this.baseURL}/api/auth/signout`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.token}`,
},
});
}
this.token = null;
localStorage.removeItem('authToken');
localStorage.removeItem('refreshToken');
}
async getSession() {
if (!this.token) return null;
const response = await fetch(`${this.baseURL}/api/auth/session`, {
headers: {
'Authorization': `Bearer ${this.token}`,
},
});
if (response.ok) {
const data = await response.json();
return data.user;
}
return null;
}
}Python
Python Authentication
import requests
import json
class MegaVaultAuth:
def __init__(self, base_url):
self.base_url = base_url
self.token = None
def sign_in(self, email, password):
url = f"{self.base_url}/api/auth/signin"
data = {"email": email, "password": password}
response = requests.post(url, json=data)
result = response.json()
if result.get('success'):
self.token = result['token']
return result['user']
else:
raise Exception(result['error']['message'])
def get_headers(self):
if not self.token:
raise Exception("Not authenticated")
return {"Authorization": f"Bearer {self.token}"}
def sign_out(self):
if self.token:
url = f"{self.base_url}/api/auth/signout"
requests.post(url, headers=self.get_headers())
self.token = None⚠️
Security Note
Never hardcode credentials or tokens in your source code. Use environment variables or secure configuration management for production applications.