GPT4Free Supported Authentication Methods: API Keys, Cookies, and HAR Files Explained
GPT4Free supports three authentication methods: API keys via environment variables, browser cookies from JSON exports or live browser extraction, and HAR files parsed for session headers and cookies.
The xtekky/gpt4free library acts as a unified interface for multiple LLM providers, each with distinct security requirements. Understanding the supported authentication methods ensures seamless access to providers that require credentials while maintaining flexibility for public endpoints. The authentication logic is centralized in g4f/tools/auth.py and g4f/cookies.py, with individual providers in g4f/Provider/ checking the needs_auth flag to determine which method to apply.
API Key Authentication via Environment Variables
How AuthManager Loads API Keys
The primary method for authenticating with commercial providers uses environment variables. In g4f/tools/auth.py, the AuthManager.load_api_key method (lines 18-31) retrieves keys named <PROVIDER>_API_KEY or defined aliases.
When a provider sets needs_auth = True, the base provider class automatically triggers this lookup. The key is then injected into request headers or the request body depending on the provider's implementation.
# Set the API key for OpenAI or compatible providers
export OPENAI_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
import g4f
# The provider automatically reads the environment variable
response = g4f.ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Explain authentication methods"}],
)
print(response)
Cookie-Based Authentication
For providers that require a logged-in browser session, GPT4Free supports cookie-based authentication through two sources: JSON cookie files and live browser extraction.
JSON Cookie Files
You can export cookies from browser extensions as JSON and place them in the default ./har_and_cookies directory (configurable via CUSTOM_COOKIES_DIR in g4f/config.py). The _parse_json_cookie_file function in g4f/cookies.py (lines 87-99) processes these files, extracting domain, name, and value fields.
Browser Cookie Extraction
The library uses the browser_cookie3 package to extract cookies directly from installed browsers (Chrome, Firefox, Edge, etc.). The get_cookies function in g4f/cookies.py retrieves the cookie map for the target domain, which providers then include in their HTTP requests.
from g4f import get_cookies
# Load cookies for the target domain (e.g., .openai.com)
cookies = get_cookies(".openai.com")
print(cookies) # {'__Secure-next-auth.session-token': '...'}
HAR File Authentication
HTTP Archive (HAR) files provide the most robust authentication method for complex web applications. When you export a HAR file from Chrome DevTools or Firefox Network Monitor after completing a successful login, GPT4Free parses this file to extract both cookies and custom headers.
Parsing HAR Files for Session Data
The _parse_har_file function in g4f/cookies.py (lines 167-182) reads the JSON structure of HAR files located in ./har_and_cookies. It extracts request headers and cookies from the entries array, merging them into the authentication store. This method captures dynamic session tokens and anti-bot headers that standard cookie exports might miss.
from g4f import get_cookies
# HAR files are parsed automatically when placed in ./har_and_cookies
cookies = get_cookies(".target-domain.com")
print(cookies) # Cookies and headers extracted from HAR entries
Provider Authentication Flow
Individual providers in g4f/Provider/ inherit from BaseProvider in g4f/providers/base_provider.py. Each provider declares a needs_auth class attribute:
- If
needs_auth = False, the provider requires no credentials and skips authentication logic. - If
needs_auth = True, the provider callsAuthManager.load_api_keyfirst. If no API key exists, it falls back toget_cookiesfor the provider's domain.
This fallback chain ensures maximum compatibility: users can switch between API keys (for stability) and session-based auth (for free tiers) without modifying provider code.
Disabling Cookie and HAR Loading
For environments where cookie extraction causes conflicts or security concerns, GPT4Free provides a CLI flag to bypass cookie/HAR parsing entirely. This forces the library to rely solely on API keys or unauthenticated providers.
# Run the CLI without reading any cookie files
g4f --ignore-cookie-files --provider OpenaiChat ...
The --ignore-cookie-files argument is defined in g4f/cli/__init__.py (line 121) and prevents read_cookie_files from executing during initialization.
Summary
- API Key Authentication: Set
<PROVIDER>_API_KEYenvironment variables;AuthManager.load_api_keying4f/tools/auth.pyhandles retrieval. - Cookie Authentication: Import JSON cookie files or use live browser extraction via
get_cookiesing4f/cookies.py. - HAR File Authentication: Place exported HAR files in
./har_and_cookies;_parse_har_fileextracts session data automatically. - Provider Logic: The
needs_authflag determines whether a provider attempts authentication, falling back from API keys to cookies/HAR data. - Security Control: Use
--ignore-cookie-filesto disable cookie/HAR parsing and enforce API-key-only operation.
Frequently Asked Questions
What is the primary authentication method for GPT4Free?
The primary method is API key authentication via environment variables. When a provider requires credentials, it first attempts to load a key named <PROVIDER>_API_KEY using AuthManager.load_api_key in g4f/tools/auth.py. This method is the most stable and reliable for production use.
How do I extract cookies for use with GPT4Free?
You have two options: manual export or automatic extraction. For manual export, save cookies as JSON from a browser extension and place the file in ./har_and_cookies. For automatic extraction, ensure browser_cookie3 is installed and call get_cookies(domain) from g4f/cookies.py, which reads cookies directly from your installed browsers.
Can I use GPT4Free without any authentication?
Yes, but only with providers that set needs_auth = False in their implementation. Many providers in g4f/Provider/ work without credentials, while others require at least one authentication method (API key, cookies, or HAR file). Check the specific provider's documentation or source code to confirm its authentication requirements.
Where does GPT4Free store parsed HAR file data?
HAR files are stored in the ./har_and_cookies directory by default, configurable via the CUSTOM_COOKIES_DIR setting in g4f/config.py. When get_cookies or the initialization routine runs, _parse_har_file in g4f/cookies.py (lines 167-182) reads these files and merges the extracted cookies and headers into the active authentication store.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →