Saltar al contenido principal

🛡️ Two-Factor Authentication Explorer

Comprehensive testing environment for 2FA setup, verification, and management. Enhance account security with TOTP authentication.


🔐 2FA Verification (Login Flow)

Use this when you've received verificationType: "2FA_CODE" from login:

POSThttps://api.swapbits.co/auth/2fa/verify

Verify 2FA code during login process

Parámetros

6-digit code from your authenticator app

Session token from login endpoint

Comando cURL

curl -X POST 'https://api.swapbits.co/auth/2fa/verify' \
  -H 'Content-Type: application/json'

🛠️ 2FA Management

Check 2FA Status

GEThttps://api.swapbits.co/auth/2fa/status
curl -X GET 'https://api.swapbits.co/auth/2fa/status' \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/json'

Setup 2FA

POSThttps://api.swapbits.co/auth/2fa/setup
curl -X POST 'https://api.swapbits.co/auth/2fa/setup' \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/json'

Disable 2FA

POSThttps://api.swapbits.co/auth/2fa/disable

Disable 2FA for your account

Autenticación

Parámetros

Current 2FA code to confirm disable

Comando cURL

curl -X POST 'https://api.swapbits.co/auth/2fa/disable' \
  -H 'Content-Type: application/json'

Response Scenarios

2FA Verification (Login)

✅ 2FA Verification Successful (Code 1008)

Authentication complete - 2FA code is valid, JWT tokens issued.

{
"code": 1008,
"message": "OTP code is valid",
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "user-uuid",
"email": "user@example.com",
"verified": true,
"twoFactorEnabled": true
}
}
}

❌ Invalid 2FA Code (Code 4005)

Verification failed - Code is incorrect or expired.

{
"code": 4005,
"message": "Invalid verification code",
"id": "error-trace-id"
}

Action: Check your authenticator app for the current code

2FA Status Check

🔍 2FA Status Response

When 2FA is enabled:

{
"code": 1000,
"message": "2FA status retrieved",
"data": {
"enabled": true,
"setupDate": "2024-01-15T10:30:00Z",
"backupCodes": 5
}
}

When 2FA is disabled:

{
"code": 1000,
"message": "2FA status retrieved",
"data": {
"enabled": false
}
}

2FA Setup

🔧 2FA Setup Response

Setup initiation successful:

{
"code": 1000,
"message": "2FA setup initiated",
"data": {
"qrCode": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
"secret": "JBSWY3DPEHPK3PXP",
"backupCodes": [
"12345678",
"87654321",
"11223344",
"44332211",
"55667788"
]
}
}

Next step: Scan QR code with authenticator app, then verify with first code


🔄 2FA Setup Flow

📱 Complete 2FA Setup Process

Step-by-step 2FA setup:

  1. Check Status → GET /auth/2fa/status to see if already enabled
  2. Initiate Setup → POST /auth/2fa/setup to get QR code and secret
  3. Scan QR Code → Use Google Authenticator, Authy, or similar app
  4. Enter Secret → Manually if QR scan doesn't work
  5. Verify Setup → POST /auth/2fa/verify with first generated code
  6. Save Backup Codes → Store securely for account recovery

Supported Authenticator Apps:

  • Google Authenticator
  • Microsoft Authenticator
  • Authy
  • 1Password
  • LastPass Authenticator

💻 Integration Examples

JavaScript/TypeScript

Complete 2FA management
interface TwoFactorManager {
checkStatus(): Promise<boolean>;
setup(): Promise<{qrCode: string; secret: string; backupCodes: string[]}>;
verify(code: string, sessionToken?: string): Promise<boolean>;
disable(code: string): Promise<boolean>;
}

class SwapBits2FA implements TwoFactorManager {
constructor(private accessToken: string) {}

async checkStatus(): Promise<boolean> {
const response = await fetch('https://api.swapbits.co/auth/2fa/status', {
headers: {
Authorization: `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
},
});

const result = await response.json();
return result.data?.enabled || false;
}

async setup() {
const response = await fetch('https://api.swapbits.co/auth/2fa/setup', {
method: 'POST',
headers: {
Authorization: `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
},
});

const result = await response.json();
if (result.code !== 1000) {
throw new Error(`Setup failed: ${result.message}`);
}

return {
qrCode: result.data.qrCode,
secret: result.data.secret,
backupCodes: result.data.backupCodes,
};
}

async verify(code: string, sessionToken?: string): Promise<boolean> {
const body = sessionToken
? { code, token: sessionToken } // Login flow
: { code }; // Setup verification

const headers: Record<string, string> = {
'Content-Type': 'application/json',
};

if (!sessionToken) {
headers.Authorization = `Bearer ${this.accessToken}`;
}

const response = await fetch('https://api.swapbits.co/auth/2fa/verify', {
method: 'POST',
headers,
body: JSON.stringify(body),
});

const result = await response.json();
return result.code === 1008;
}

async disable(code: string): Promise<boolean> {
const response = await fetch('https://api.swapbits.co/auth/2fa/disable', {
method: 'POST',
headers: {
Authorization: `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
});

const result = await response.json();
return result.code === 1007; // 2FA disabled successfully
}
}

// Usage examples
const twoFA = new SwapBits2FA('your-access-token');

// Check if 2FA is enabled
const isEnabled = await twoFA.checkStatus();
console.log('2FA enabled:', isEnabled);

// Setup 2FA
if (!isEnabled) {
const setup = await twoFA.setup();
console.log('Scan this QR code:', setup.qrCode);
console.log('Or enter this secret:', setup.secret);
console.log('Backup codes:', setup.backupCodes);

// After scanning, verify with first code
const firstCode = prompt('Enter first code from app:');
const verified = await twoFA.verify(firstCode);
console.log('Setup verified:', verified);
}

// During login (when you get verificationType: "2FA_CODE")
async function handle2FALogin(sessionToken: string) {
const code = prompt('Enter 2FA code:');
const verified = await twoFA.verify(code, sessionToken);

if (verified) {
console.log('Login successful!');
// Tokens will be in the response
} else {
console.log('Invalid 2FA code');
}
}

Python

2FA management with Python
import requests
import qrcode
from io import BytesIO
import base64

class SwapBits2FA:
def __init__(self, access_token: str = None):
self.access_token = access_token
self.base_url = 'https://api.swapbits.co'

def check_status(self) -> bool:
"""Check if 2FA is enabled for the user"""
response = requests.get(
f'{self.base_url}/auth/2fa/status',
headers={'Authorization': f'Bearer {self.access_token}'}
)
result = response.json()
return result.get('data', {}).get('enabled', False)

def setup(self) -> dict:
"""Initiate 2FA setup and get QR code"""
response = requests.post(
f'{self.base_url}/auth/2fa/setup',
headers={'Authorization': f'Bearer {self.access_token}'}
)
result = response.json()

if result['code'] != 1000:
raise Exception(f"Setup failed: {result['message']}")

return {
'qr_code': result['data']['qrCode'],
'secret': result['data']['secret'],
'backup_codes': result['data']['backupCodes']
}

def verify(self, code: str, session_token: str = None) -> bool:
"""Verify 2FA code (either during setup or login)"""
data = {'code': code}
headers = {'Content-Type': 'application/json'}

if session_token:
# Login flow
data['token'] = session_token
else:
# Setup verification
headers['Authorization'] = f'Bearer {self.access_token}'

response = requests.post(
f'{self.base_url}/auth/2fa/verify',
json=data,
headers=headers
)
result = response.json()
return result['code'] == 1008

def disable(self, code: str) -> bool:
"""Disable 2FA for the account"""
response = requests.post(
f'{self.base_url}/auth/2fa/disable',
json={'code': code},
headers={'Authorization': f'Bearer {self.access_token}'}
)
result = response.json()
return result['code'] == 1007

def save_qr_code(self, qr_data: str, filename: str = '2fa_qr.png'):
"""Save QR code to file for easy scanning"""
# Remove data URL prefix
qr_data = qr_data.split(',')[1]
qr_bytes = base64.b64decode(qr_data)

with open(filename, 'wb') as f:
f.write(qr_bytes)
print(f"QR code saved to {filename}")

# Usage
twofa = SwapBits2FA('your-access-token')

# Check current status
enabled = twofa.check_status()
print(f"2FA currently enabled: {enabled}")

# Setup 2FA if not enabled
if not enabled:
setup_data = twofa.setup()
print(f"Secret key: {setup_data['secret']}")
print(f"Backup codes: {setup_data['backup_codes']}")

# Save QR code for scanning
twofa.save_qr_code(setup_data['qr_code'])

# Verify setup with first code
first_code = input("Enter first code from authenticator app: ")
verified = twofa.verify(first_code)
print(f"Setup verified: {verified}")


🆘 Troubleshooting

🔧 Common 2FA Issues & Solutions

Problem: QR code won't scan Solution: Enter the secret key manually in your authenticator app

Problem: Code always invalid during login Solution: Check device time sync, ensure 6-digit code, try previous/next code

Problem: Lost access to authenticator device Solution: Use backup codes from setup, contact support if codes unavailable

Problem: Can't disable 2FA Solution: Ensure you're using current valid code, not expired one

Problem: Time sync issues Solution: Sync your device clock, authenticator apps require accurate time