API Authentication

Hướng dẫn sử dụng API tokens để truy cập các AI services một cách bảo mật

Tổng quan

Tất cả các AI services trong hệ thống yêu cầu API token để xác thực. API token giúp:

Lấy API Token:
Liên hệ admin hoặc tạo token tại: Admin Token Management

Lưu ý: Không có demo token công khai. Liên hệ admin để được cấp token hợp lệ.

Cách sử dụng Token

Có 3 cách để gửi API token trong request:

1. Authorization Header (Recommended) ⭐

Đây là phương thức được khuyến nghị - Token được gửi trong HTTP header, bảo mật và chuẩn hóa.

# Thay YOUR_API_TOKEN bằng token thật từ admin
curl -X POST "https://pnt.badt.vn/medical_transcribe/transcribe" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -F "audio_file=@audio.wav"

2. X-API-Key Header (Alternative)

Một số services hỗ trợ custom header X-API-Key

# Thay YOUR_API_TOKEN bằng token thật
curl -X POST "https://pnt.badt.vn/face_recognition/recognize_faces" \
  -H "X-API-Key: YOUR_API_TOKEN" \
  -F "file=@photo.jpg"

3. Query Parameter (Not Recommended for Production) ⚠️

Chỉ dùng cho testing - Token xuất hiện trong URL có thể bị log và cache, không an toàn.

# KHÔNG khuyến nghị dùng trong production!
curl "https://pnt.badt.vn/codefinder/search?q=diabetes&api_key=YOUR_API_TOKEN"
Lưu ý bảo mật:
• Không chia sẻ token công khai
• Không commit token vào source code
• Sử dụng environment variables để lưu token
• Rotate token định kỳ

Code Examples

Python - Best Practice ⭐

import requests
import os

# ===== BƯỚC 1: LẤY API TOKEN =====
# Khuyến nghị: Lưu token trong environment variable
# Chạy: export API_AI_TOKEN="your_token_here"
API_TOKEN = os.getenv('API_AI_TOKEN')


if not API_TOKEN:
    raise ValueError("⚠️ API_TOKEN chưa được set! Run: export API_AI_TOKEN='your_token'")

# ===== BƯỚC 2: TẠO HEADERS VỚI TOKEN =====
# Authorization: Bearer  là phương thức chuẩn
headers = {
    'Authorization': f'Bearer {API_TOKEN}'
}

# ===== BƯỚC 3: GỌI API VỚI TOKEN =====
# Example: Medical Transcribe
try:
    with open('audio.wav', 'rb') as f:
        files = {'audio_file': f}
        response = requests.post(
            'https://pnt.badt.vn/medical_transcribe/transcribe',
            headers=headers,  # ← Token được gửi ở đây!
            files=files
        )
        
        # Check authentication
        if response.status_code == 401:
            print("❌ Token không hợp lệ hoặc chưa cung cấp!")
        elif response.status_code == 403:
            print("❌ Token hết hạn hoặc không có quyền!")
        elif response.status_code == 200:
            result = response.json()
            print(f"✅ Transcription: {result['transcription']}")
        else:
            print(f"⚠️ Error {response.status_code}: {response.text}")
            
except FileNotFoundError:
    print("❌ File audio.wav không tồn tại!")
except Exception as e:
    print(f"❌ Lỗi: {e}")

JavaScript (Node.js) - Best Practice ⭐

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

// ===== BƯỚC 1: LẤY API TOKEN =====
// Khuyến nghị: Lưu trong .env file
const API_TOKEN = process.env.API_AI_TOKEN;

if (!API_TOKEN) {
    throw new Error('⚠️ API_TOKEN chưa được set! Set: export API_AI_TOKEN="your_token"');
}

// ===== BƯỚC 2: TẠO REQUEST VỚI TOKEN =====
// Example: Face Recognition
const form = new FormData();
form.append('file', fs.createReadStream('photo.jpg'));

axios.post('https://pnt.badt.vn/face_recognition/recognize_faces', form, {
    headers: {
        'Authorization': `Bearer ${API_TOKEN}`,  // ← Token ở đây!
        ...form.getHeaders()
    }
})
.then(response => {
    console.log('✅ Success:', response.data);
})
.catch(error => {
    // Handle authentication errors
    if (error.response?.status === 401) {
        console.error('❌ Token không hợp lệ!');
    } else if (error.response?.status === 403) {
        console.error('❌ Token hết hạn hoặc không có quyền!');
    } else {
        console.error('❌ Error:', error.response?.data || error.message);
    }
});

PHP - Best Practice ⭐

⚠️ API_TOKEN chưa được set! Run: export API_AI_TOKEN="your_token"