Trong thế giới AI đang bùng nổ, việc bảo mật API endpoints không còn là tùy chọn mà là yêu cầu bắt buộc. Bài viết này sẽ hướng dẫn bạn cách triển khai OAuth2 để bảo vệ AI API của mình, đồng thời so sánh chi phí và hiệu suất giữa các nhà cung cấp.
So Sánh Chi Phí: HolySheep AI vs Official API vs Dịch Vụ Relay
Trước khi đi vào chi tiết kỹ thuật, hãy cùng xem bảng so sánh chi phí thực tế để hiểu tại sao HolySheep AI đang trở thành lựa chọn hàng đầu của cộng đồng developer:
| Tiêu chí | HolySheep AI | Official API | Dịch vụ Relay khác |
|---|---|---|---|
| Tỷ giá | ¥1 = $1 (85%+ tiết kiệm) | $1 = $1 (giá gốc) | Tùy nhà cung cấp |
| Thanh toán | WeChat, Alipay, USDT | Visa/MasterCard | Hạn chế |
| Độ trễ trung bình | <50ms | 100-300ms | 80-200ms |
| Tín dụng miễn phí | Có khi đăng ký | $5 trial | Không |
| GPT-4.1 / MTok | $8 | $60 | $15-25 |
| Claude Sonnet 4.5 / MTok | $15 | $45 | $20-30 |
| Gemini 2.5 Flash / MTok | $2.50 | $10 | $5-8 |
| DeepSeek V3.2 / MTok | $0.42 | $2 | $1-1.5 |
Như bạn thấy, HolySheep AI mang lại mức tiết kiệm lên đến 85% so với API chính thức, đồng thời hỗ trợ các phương thức thanh toán phổ biến tại châu Á và có độ trễ thấp nhất thị trường.
OAuth2 Là Gì và Tại Sao Cần Thiết?
OAuth2 (Open Authorization 2.0) là giao thức ủy quyền tiêu chuẩn cho phép các ứng dụng truy cập tài nguyên thay mặt người dùng mà không cần chia sẻ mật khẩu. Khi nói đến AI API endpoints, OAuth2 giúp:
- Mã hóa truy cập API với access tokens có thời hạn
- Quản lý quyền truy cập theo scope cụ thể
- Hỗ trợ refresh tokens để duy trì phiên làm việc
- Giới hạn rate limiting theo từng ứng dụng
- Thu hồi quyền truy cập tức thì khi cần
Triển Khai OAuth2 Server Với Node.js
Trong phần này, tôi sẽ chia sẻ cách triển khai OAuth2 server hoàn chỉnh cho AI API endpoints. Đây là kinh nghiệm thực chiến từ dự án production của tôi với hơn 10,000 requests mỗi ngày.
// oauth2-server.js - Triển khai OAuth2 Server hoàn chỉnh
const express = require('express');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const rateLimit = require('express-rate-limit');
const app = express();
app.use(express.json());
// Cấu hình HolySheep AI API
const HOLYSHEEP_CONFIG = {
base_url: 'https://api.holysheep.ai/v1',
api_key: process.env.HOLYSHEEP_API_KEY
};
// In-memory storage cho demo (production nên dùng Redis/PostgreSQL)
const clients = new Map(); // client_id -> { client_secret, scopes, name }
const accessTokens = new Map(); // access_token -> { client_id, user_id, scopes, expires_at }
const refreshTokens = new Map(); // refresh_token -> { client_id, user_id, scopes }
const users = new Map(); // user_id -> { username, password_hash, api_quota }
// Khởi tạo client mẫu
clients.set('ai-dashboard-app', {
client_secret: 'super_secret_client_secret_hash',
scopes: ['chat:read', 'chat:write', 'embedding:read'],
name: 'AI Dashboard Application'
});
// Tạo token ngẫu nhiên an toàn
function generateToken(length = 64) {
return crypto.randomBytes(length).toString('hex');
}
// Hash mật khẩu với bcrypt
const bcrypt = require('bcrypt');
const SALT_ROUNDS = 12;
async function hashPassword(password) {
return bcrypt.hash(password, SALT_ROUNDS);
}
async function verifyPassword(password, hash) {
return bcrypt.compare(password, hash);
}
// Middleware xác thực OAuth2
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
const tokenData = accessTokens.get(token);
if (!tokenData) {
return res.status(401).json({ error: 'Invalid access token' });
}
if (new Date() > tokenData.expires_at) {
accessTokens.delete(token);
return res.status(401).json({ error: 'Token expired' });
}
req.auth = tokenData;
next();
}
// Middleware kiểm tra scope
function requireScope(requiredScope) {
return (req, res, next) => {
if (!req.auth.scopes.includes(requiredScope)) {
return res.status(403).json({
error: Missing required scope: ${requiredScope}
});
}
next();
};
}
// Rate limiter cho endpoint auth
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 phút
max: 100, // 100 requests mỗi 15 phút
message: { error: 'Too many authentication attempts' }
});
// ============ OAUTH2 ENDPOINTS ============
// POST /oauth/token - Lấy access token
app.post('/oauth/token', authLimiter, async (req, res) => {
const { grant_type, client_id, client_secret, username, password, refresh_token, scope } = req.body;
try {
if (grant_type === 'client_credentials') {
// Client Credentials Grant
const client = clients.get(client_id);
if (!client || client.client_secret !== client_secret) {
return res.status(401).json({ error: 'Invalid client credentials' });
}
const accessToken = generateToken();
const expiresIn = 3600; // 1 giờ
accessTokens.set(accessToken, {
client_id,
user_id: null,
scopes: client.scopes,
expires_at: new Date(Date.now() + expiresIn * 1000)
});
return res.json({
access_token: accessToken,
token_type: 'Bearer',
expires_in: expiresIn,
scope: client.scopes.join(' ')
});
} else if (grant_type === 'password') {
// Resource Owner Password Credentials Grant
const client = clients.get(client_id);
if (!client || client.client_secret !== client_secret) {
return res.status(401).json({ error: 'Invalid client credentials' });
}
// Xác thực user (demo)
const user = users.get(username);
if (!user || !(await verifyPassword(password, user.password_hash))) {
return res.status(401).json({ error: 'Invalid username or password' });
}
// Kiểm tra và merge scopes
const requestedScopes = scope ? scope.split(' ') : client.scopes;
const validScopes = requestedScopes.filter(s => client.scopes.includes(s));
const accessToken = generateToken();
const refreshTokenValue = generateToken();
const expiresIn = 3600;
accessTokens.set(accessToken, {
client_id,
user_id: username,
scopes: validScopes,
expires_at: new Date(Date.now() + expiresIn * 1000)
});
refreshTokens.set(refreshTokenValue, {
client_id,
user_id: username,
scopes: validScopes
});
return res.json({
access_token: accessToken,
token_type: 'Bearer',
expires_in: expiresIn,
refresh_token: refreshTokenValue,
scope: validScopes.join(' ')
});
} else if (grant_type === 'refresh_token') {
// Refresh Token Grant
const storedRefresh = refreshTokens.get(refresh_token);
if (!storedRefresh) {
return res.status(401).json({ error: 'Invalid refresh token' });
}
const client = clients.get(storedRefresh.client_id);
const requestedScopes = scope ? scope.split(' ') : storedRefresh.scopes;
const validScopes = requestedScopes.filter(s => client.scopes.includes(s));
const accessToken = generateToken();
const expiresIn = 3600;
accessTokens.set(accessToken, {
client_id: storedRefresh.client_id,
user_id: storedRefresh.user_id,
scopes: validScopes,
expires_at: new Date(Date.now() + expiresIn * 1000)
});
return res.json({
access_token: accessToken,
token_type: 'Bearer',
expires_in: expiresIn,
scope: validScopes.join(' ')
});
} else {
return res.status(400).json({ error: 'Unsupported grant_type' });
}
} catch (error) {
console.error('Token error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// POST /oauth/revoke - Thu hồi token
app.post('/oauth/revoke', (req, res) => {
const { token } = req.body;
if (accessTokens.has(token)) {
accessTokens.delete(token);
}
if (refreshTokens.has(token)) {
refreshTokens.delete(token);
}
res.json({ success: true });
});
// ============ AI API PROXY ENDPOINTS ============
// Proxy chat completion đến HolySheep AI
app.post('/api/v1/chat/completions', authenticateToken, requireScope('chat:write'),
rateLimit({ windowMs: 60000, max: 60 }), // 60 requests/phút
async (req, res) => {
try {
const { messages, model, temperature, max_tokens } = req.body;
const response = await fetch(${HOLYSHEEP_CONFIG.base_url}/chat/completions, {
method: 'POST',
headers: {
'Authorization': Bearer ${HOLYSHEEP_CONFIG.api_key},
'Content-Type': 'application/json',
'X-Client-ID': req.auth.client_id,
'X-User-ID': req.auth.user_id
},
body: JSON.stringify({
model: model || 'gpt-4.1',
messages,
temperature: temperature || 0.7,
max_tokens: max_tokens || 1000
})
});
const data = await response.json();
res.json(data);
} catch (error) {
console.error('HolySheep API error:', error);
res.status(502).json({ error: 'AI service unavailable' });
}
}
);
// Proxy embeddings đến HolySheep AI
app.post('/api/v1/embeddings', authenticateToken, requireScope('embedding:read'),
rateLimit({ windowMs: 60000, max: 120 }),
async (req, res) => {
try {
const { input, model } = req.body;
const response = await fetch(${HOLYSHEEP_CONFIG.base_url}/embeddings, {
method: 'POST',
headers: {
'Authorization': Bearer ${HOLYSHEEP_CONFIG.api_key},
'Content-Type': 'application/json',
'X-Client-ID': req.auth.client_id
},
body: JSON.stringify({
model: model || 'text-embedding-3-small',
input
})
});
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Embedding API error:', error);
res.status(502).json({ error: 'Embedding service unavailable' });
}
}
);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
active_tokens: accessTokens.size,
clients: clients.size
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(OAuth2 Server running on port ${PORT});
console.log(HolySheep AI endpoint: ${HOLYSHEEP_CONFIG.base_url});
});
module.exports = app;
Client SDK Cho Ứng Dụng Tiêu Dùng
Sau khi triển khai OAuth2 server, bạn cần một client SDK để các ứng dụng tiêu dùng dễ dàng tích hợp. Dưới đây là SDK hoàn chỉnh với TypeScript:
// holysheep-oauth-client.ts - TypeScript SDK cho OAuth2 Client
import axios, { AxiosInstance, AxiosError } from 'axios';
interface TokenResponse {
access_token: string;
token_type: string;
expires_in: number;
refresh_token?: string;
scope: string;
}
interface OAuthConfig {
serverUrl: string;
clientId: string;
clientSecret: string;
redirectUri?: string;
scopes: string[];
}
interface RequestConfig {
headers?: Record;
params?: Record;
}
export class HolySheepOAuthClient {
private httpClient: AxiosInstance;
private config: OAuthConfig;
private accessToken: string | null = null;
private refreshToken: string | null = null;
private tokenExpiresAt: Date | null = null;
private refreshPromise: Promise | null = null;
constructor(config: OAuthConfig) {
this.config = config;
this.httpClient = axios.create({
baseURL: config.serverUrl,
timeout: 30000,
});
}
// Lấy authorization URL cho OAuth2 authorization code flow
getAuthorizationUrl(state?: string): string {
const params = new URLSearchParams({
client_id: this.config.clientId,
redirect_uri: this.config.redirectUri || '',
response_type: 'code',
scope: this.config.scopes.join(' '),
});
if (state) {
params.append('state', state);
}
return ${this.config.serverUrl}/oauth/authorize?${params.toString()};
}
// Lấy access token bằng authorization code
async exchangeCodeForToken(code: string): Promise {
const response = await this.httpClient.post('/oauth/token', {
grant_type: 'authorization_code',
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
code,
redirect_uri: this.config.redirectUri,
});
this.setTokenData(response.data);
return response.data;
}
// Lấy access token bằng username/password
async login(username: string, password: string): Promise {
const response = await this.httpClient.post('/oauth/token', {
grant_type: 'password',
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
username,
password,
scope: this.config.scopes.join(' '),
});
this.setTokenData(response.data);
return response.data;
}
// Lấy access token bằng client credentials
async authenticateClient(): Promise {
const response = await this.httpClient.post('/oauth/token', {
grant_type: 'client_credentials',
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
scope: this.config.scopes.join(' '),
});
this.setTokenData(response.data);
return response.data;
}
// Làm mới access token
private async refreshAccessToken(): Promise {
if (!this.refreshToken) {
throw new Error('No refresh token available');
}
const response = await this.httpClient.post('/oauth/token', {
grant_type: 'refresh_token',
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
refresh_token: this.refreshToken,
});
this.setTokenData(response.data);
return response.data.access_token;
}
// Lấy token hiện tại (tự động refresh nếu hết hạn)
async getValidToken(): Promise {
if (!this.accessToken) {
throw new Error('Not authenticated. Call login() or authenticateClient() first.');
}
// Kiểm tra token còn hạn không (buffer 5 phút)
if (this.tokenExpiresAt &&
new Date() < new Date(this.tokenExpiresAt.getTime() - 5 * 60 * 1000)) {
return this.accessToken;
}
// Refresh token nếu hết hạn hoặc sắp hết hạn
if (this.refreshToken) {
// Tránh gọi refresh nhiều lần cùng lúc
if (!this.refreshPromise) {
this.refreshPromise = this.refreshAccessToken()
.finally(() => {
this.refreshPromise = null;
});
}
return this.refreshPromise;
}
throw new Error('Token expired and no refresh token available');
}
// Gọi API với access token tự động
async request(method: 'GET' | 'POST' | 'PUT' | 'DELETE',
path: string,
data?: any,
config?: RequestConfig): Promise {
const token = await this.getValidToken();
try {
const response = await this.httpClient.request({
method,
url: path,
data,
headers: {
'Authorization': Bearer ${token},
...config?.headers,
},
params: config?.params,
});
return response.data;
} catch (error) {
if (error instanceof AxiosError && error.response?.status === 401) {
// Token có thể bị thu hồi phía server
if (this.refreshToken) {
this.accessToken = null;
const newToken = await this.refreshAccessToken();
// Retry request với token mới
const response = await this.httpClient.request({
method,
url: path,
data,
headers: {
'Authorization': Bearer ${newToken},
...config?.headers,
},
params: config?.params,
});
return response.data;
}
}
throw error;
}
}
// Đăng xuất - thu hồi token
async logout(): Promise {
if (this.accessToken) {
try {
await this.httpClient.post('/oauth/revoke', {
token: this.accessToken,
});
} catch (error) {
console.warn('Token revocation failed:', error);
}
}
this.accessToken = null;
this.refreshToken = null;
this.tokenExpiresAt = null;
}
// Kiểm tra trạng thái đăng nhập
isAuthenticated(): boolean {
return !!this.accessToken && !!this.tokenExpiresAt &&
new Date() < this.tokenExpiresAt;
}
private setTokenData(data: TokenResponse): void {
this.accessToken = data.access_token;
this.tokenExpiresAt = new Date(Date.now() + data.expires_in * 1000);
if (data.refresh_token) {
this.refreshToken = data.refresh_token;
}
}
}
// ============ Ví dụ sử dụng ============
async function main() {
// Khởi tạo client với cấu hình OAuth2
const client = new HolySheepOAuthClient({
serverUrl: 'https://api.your-oauth-server.com',
clientId: 'ai-dashboard-app',
clientSecret: 'super_secret_client_secret_hash',
scopes: ['chat:read', 'chat:write', 'embedding:read'],
});
try {
// Đăng nhập bằng username/password
await client.login('[email protected]', 'user_password');
console.log('Đăng nhập thành công!');
// Gọi API chat completion
const chatResponse = await client.request('POST', '/api/v1/chat/completions', {
model: 'gpt-4.1',
messages: [
{ role: 'system', content: 'Bạn là trợ lý AI hữu ích.' },
{ role: 'user', content: 'Xin chào, hãy giới thiệu về HolySheep AI' }
],
temperature: 0.7,
max_tokens: 500
});
console.log('Chat response:', chatResponse);
// Gọi API embeddings
const embedResponse = await client.request('POST', '/api/v1/embeddings', {
model: 'text-embedding-3-small',
input: 'HolySheep AI - Giải pháp AI tiết kiệm chi phí'
});
console.log('Embedding dimensions:', embedResponse.data?.[0]?.embedding?.length);
// Đăng xuất
await client.logout();
console.log('Đăng xuất thành công!');
} catch (error) {
if (error instanceof AxiosError) {
console.error('API Error:', error.response?.data || error.message);
} else {
console.error('Error:', error);
}
}
}
// Export cho module usage
export default HolySheepOAuthClient;
Triển Khai OAuth2 Với Python Và FastAPI
Đối với những ai thích sử dụng Python, FastAPI là lựa chọn tuyệt vời với hiệu suất cao và syntax hiện đại. Dưới đây là implementation hoàn chỉnh:
# oauth2_fastapi_server.py - OAuth2 Server với FastAPI
from fastapi import FastAPI, HTTPException, Depends, status, Request
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel, Field
from passlib.context import CryptContext
from jose import JWTError, jwt
from datetime import datetime, timedelta
from typing import Optional, List
import httpx
import secrets
import time
Cấu hình
HOLYSHEEP_CONFIG = {
"base_url": "https://api.holysheep.ai/v1",
"api_key": "YOUR_HOLYSHEEP_API_KEY"
}
SECRET_KEY = secrets.token_hex(32)
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60
Models
class Token(BaseModel):
access_token: str
token_type: str
expires_in: int
refresh_token: Optional[str] = None
scope: str
class TokenData(BaseModel):
client_id: Optional[str] = None
user_id: Optional[str] = None
scopes: List[str] = []
class ChatMessage(BaseModel):
role: str
content: str
class ChatRequest(BaseModel):
model: str = "gpt-4.1"
messages: List[ChatMessage]
temperature: float = Field(default=0.7, ge=0, le=2)
max_tokens: int = Field(default=1000, ge=1, le=32000)
Password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="oauth/token")
In-memory storage (dùng Redis/PostgreSQL trong production)
clients_db = {
"ai-dashboard-app": {
"client_secret": "super_secret_hash",
"scopes": ["chat:read", "chat:write", "embedding:read"],
"name": "AI Dashboard"
}
}
tokens_db = {} # token -> {client_id, user_id, scopes, expires_at}
refresh_tokens_db = {} # refresh_token -> {client_id, user_id, scopes}
users_db = {} # user_id -> {username, hashed_password, quota}
App
app = FastAPI(title="OAuth2 AI Proxy Server", version="1.0.0")
Helper functions
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
to_encode.update({"exp": expire, "iat": datetime.utcnow()})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
async def get_current_client(token: str = Depends(oauth2_scheme)) -> TokenData:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
# Kiểm tra token trong database trước
token_info = tokens_db.get(token)
if not token_info:
raise credentials_exception
if datetime.utcnow() > token_info["expires_at"]:
del tokens_db[token]
raise credentials_exception
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return TokenData(
client_id=token_info["client_id"],
user_id=token_info["user_id"],
scopes=token_info["scopes"]
)
except JWTError:
raise credentials_exception
def require_scope(required_scope: str):
async def scope_checker(current_client: TokenData = Depends(get_current_client)):
if required_scope not in current_client.scopes:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Missing required scope: {required_scope}"
)
return current_client
return scope_checker
============ OAUTH2 ENDPOINTS ============
@app.post("/oauth/token", response_model=Token)
async def get_token(
form_data: OAuth2PasswordRequestForm = Depends()
):
"""OAuth2 Token Endpoint - hỗ trợ password và client_credentials"""
client = clients_db.get(form_data.client_id)
if not client or client["client_secret"] != form_data.client_secret:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid client credentials"
)
scopes = form_data.scopes or client["scopes"]
valid_scopes = [s for s in scopes if s in client["scopes"]]
if form_data.username:
# Password grant - xác thực user
user = users_db.get(form_data.username)
if not user or not verify_password(form_data.password or "", user["hashed_password"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid username or password"
)
user_id = form_data.username
else:
user_id = None
# Tạo tokens
expires_in = ACCESS_TOKEN_EXPIRE_MINUTES * 60
expires_at = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = secrets.token_urlsafe(64)
refresh_token = secrets.token_urlsafe(64)
# Lưu vào database
tokens_db[access_token] = {
"client_id": form_data.client_id,
"user_id": user_id,
"scopes": valid_scopes,
"expires_at": expires_at
}
refresh_tokens_db[refresh_token] = {
"client_id": form_data.client_id,
"user_id": user_id,
"scopes": valid_scopes
}
return Token(
access_token=access_token,
token_type="Bearer",
expires_in=expires_in,
refresh_token=refresh_token,
scope=" ".join(valid_scopes)
)
@app.post("/oauth/refresh")
async def refresh_token(refresh_token: str):
"""Refresh access token"""
stored = refresh_tokens_db.get(refresh_token)
if not stored:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid refresh token"
)
client = clients_db.get(stored["client_id"])
expires_in = ACCESS_TOKEN_EXPIRE_MINUTES * 60
expires_at = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
new_access_token = secrets.token_urlsafe(64)
tokens_db[new_access_token] = {
"client_id": stored["client_id"],
"user_id": stored["user_id"],
"scopes": stored["scopes"],
"expires_at": expires_at
}
return {
"access_token": new_access_token,
"token_type": "Bearer",
"expires_in": expires_in,
"scope": " ".join(stored["scopes"])
}
@app.post("/oauth/revoke")
async def revoke_token(token: str):
"""Thu hồi token"""
if token in tokens_db:
del tokens_db[token]
if token in refresh_tokens_db:
del refresh_tokens_db[token]
return {"success": True}
============ AI API PROXY ENDPOINTS ============
@app.post("/api/v1/chat/completions")
async def chat_completions(
request: ChatRequest,
current: TokenData = Depends(require_scope("chat:write"))
):
"""Proxy chat completions đến HolySheep AI"""
async with httpx.AsyncClient(timeout=60.0) as client:
try:
response = await client.post(
f"{HOLYSHEEP_CONFIG['base_url']}/chat/completions",
headers={
"Authorization": f"Bearer {HOLYSHEEP_CONFIG['api_key']}",
"Content-Type": "application/json",
"X-Client-ID": current.client_id or "",
"X-User-ID": current.user_id or ""
},
json={
"model": request.model,
"messages": [m.dict() for m in request.messages],
"temperature": request.temperature,
"max_tokens": request.max_tokens
}
)
if response.status_code != 200:
raise HTTPException(
status_code=502,
detail=f"HolySheep API error: {response.text}"
)
return response.json()
except httpx.TimeoutException:
raise HTTPException(
status_code=504,
detail="HolySheep AI timeout"
)
except httpx.HTTPError as e:
raise HTTPException(
status_code=502,
detail=f"Connection error: {str(e)}"
)
@app.post("/api/v1/embeddings")
async def embeddings(
input: str | List[str],
model: str = "text-embedding-3-small",
current: TokenData = Depends(require_scope("embedding:read"))
):
"""Proxy embeddings đến HolySheep AI"""
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
f"{HOLYSHEEP_CONFIG['base_url']}/embeddings",
headers={
"Authorization": f"Bearer {HOLYSHEEP_CONFIG['api_key']}",
"Content-Type": "application/json"
},
json={
"model": model,
"input": input
}
)
return response.json()
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"timestamp": datetime.utcnow().isoformat(),
"active_tokens": len(tokens_db),
"clients": len(clients_db)
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Best Practices Bảo Mật OAuth2
Qua kinh nghiệm triển khai nhiều dự án, tôi chia sẻ những best practices quan trọng nhất:
- Sử dụng HTTPS bắt buộc: Tất cả OAuth2 endpoints phải chạy qua HTTPS để mã hóa dữ liệu truyền tải
- Token có th�