This page documents the authentication and security mechanisms for the g4f HTTP API server (FastAPI and Flask backends). It covers API key management, token encryption, request authorization, and access control patterns.
Scope: This page focuses on authentication for the HTTP API endpoints exposed by g4f's FastAPI server (port 1337) and Flask GUI backend (port 8080). For provider-specific authentication (cookies, HAR files, OAuth), see Authentication & Session Management.
The g4f HTTP API implements a multi-layered authentication system supporting:
All authentication is handled by a FastAPI middleware that intercepts requests before they reach endpoint handlers.
Sources: g4f/api/__init__.py1-307
Sources: g4f/api/__init__.py230-306
The primary API key is configured via the G4F_API_KEY environment variable, loaded during application startup:
When set, the key is masked in logs:
| Property | Type | Description |
|---|---|---|
g4f_api_key | Optional[str] | Static API key for authentication |
ignore_cookie_files | bool | Whether to skip cookie file loading |
demo | bool | Enable demo mode with relaxed auth |
gui | bool | Mount Flask GUI app |
Sources: g4f/api/__init__.py177-194
Clients can provide API keys in two header formats:
g4f-api-key: your-api-key-here
Authorization: Bearer your-api-key-here
The middleware tries the custom header first, then falls back to the Bearer token.
Sources: g4f/api/__init__.py210-244
For enhanced security, g4f supports RSA-encrypted API keys that can be validated without storing the plaintext key server-side.
Sources: g4f/api/__init__.py233-281 g4f/gui/server/crypto.py
The server attempts to decrypt the API key using the RSA private key:
The decrypted payload format is: {expires_timestamp}:{user_identifier}
As a fallback, the server tries session key decryption for JSON-encoded tokens:
The JSON payload must contain:
data: Encrypted timestampuser: User identifierreferrer: Request origin (required)After decryption, the server validates the expiration timestamp:
The server enforces constraints on user identifiers to prevent abuse:
This prevents "screaming" user names (6+ consecutive uppercase characters).
Sources: g4f/api/__init__.py254-281
For GUI access without API keys, the server supports HTTP Basic authentication:
The password must match the configured G4F API key. The username is returned for logging purposes.
Sources: g4f/api/__init__.py214-228
Demo mode (AppConfig.demo = True) enables public access with user tracking:
| Source | Priority | Format |
|---|---|---|
x-user header | 1 | Custom identifier |
X-Forwarded-For header | 2 | First 4 chars of IP |
Cf-Ipcountry header | - | Country prefix |
Final format: {country}:{user} or {user}
Sources: g4f/api/__init__.py248-252
The authorization middleware enforces different requirements based on request paths:
Sources: g4f/api/__init__.py284-299
| Path Pattern | Auth Requirement | Exceptions |
|---|---|---|
/v1/* | API key required | /v1/models (public) |
/api/* | API key required | /api/*/models (public) |
/backend-api/v2/upload_cookies | API key required (demo) | None |
/backend-api/* | HTTP Basic or API key | Demo mode bypasses |
/chat/* | HTTP Basic or API key | Demo mode bypasses |
/images/* | No auth required | - |
/media/* | No auth required | - |
Sources: g4f/api/__init__.py284-299
This function modifies request headers to propagate authentication context to downstream handlers.
Sources: g4f/api/__init__.py196-204 g4f/api/__init__.py230-307
The API allows all origins, methods, and headers for maximum client compatibility.
The API uses FastAPI's built-in validation with custom error formatting:
Cookie file uploads are protected by:
ignore_cookie_files flag check.json, .har)os.path.basename()Sources: g4f/api/__init__.py117-125 g4f/api/__init__.py308-322 g4f/api/__init__.py725-744
| Method | Parameters | Returns |
|---|---|---|
from_exception() | exception, config, status_code | ErrorResponse |
from_message() | message, status_code, headers | ErrorResponse |
| Code | Constant | Usage |
|---|---|---|
| 401 | HTTP_401_UNAUTHORIZED | Missing/invalid API key |
| 403 | HTTP_403_FORBIDDEN | Invalid user or access denied |
| 422 | HTTP_422_UNPROCESSABLE_ENTITY | Validation error |
| 429 | HTTP_429_TOO_MANY_REQUESTS | Rate limit exceeded |
| 500 | HTTP_500_INTERNAL_SERVER_ERROR | Internal error |
Sources: g4f/api/__init__.py161-175 g4f/api/__init__.py22-30
The API uses constant-time comparison to prevent timing attacks:
g4f/api/__init__.py219-220 g4f/api/__init__.py253
''.join(['*' for _ in range(len(key))])Cookie files are loaded during startup unless ignore_cookie_files is set:
Sources: g4f/api/__init__.py96-98 g4f/api/__init__.py219-220 g4f/api/__init__.py232 g4f/api/__init__.py253
While this page covers HTTP API authentication, provider-specific authentication (HAR files, browser cookies, OAuth) is handled separately:
The HTTP API authentication determines who can use the API, while provider authentication determines which external services can be accessed.
Refresh this wiki