xtekky/gpt4free · error · NoValidHarFileError

No access token found in .har files

Error message

No access token found in .har files

What it means

MicrosoftDesigner.readHAR() scans all .har files on disk for requests whose URL starts with the designer endpoint and extracts the Authorization bearer token; if no HAR file yields one, NoValidHarFileError is raised. It means the provider could not find designer credentials in any exported browser capture.

Source

Thrown at g4f/Provider/needs_auth/MicrosoftDesigner.py:168

def readHAR(url: str) -> tuple[str, str]:
    api_key = None
    user_agent = None
    for path in get_har_files():
        with open(path, "rb") as file:
            try:
                harFile = json.loads(file.read())
            except json.JSONDecodeError:
                # Error: not a HAR file!
                continue
            for v in harFile["log"]["entries"]:
                if v["request"]["url"].startswith(url):
                    v_headers = get_headers(v)
                    if "authorization" in v_headers:
                        api_key = v_headers["authorization"].split(maxsplit=1).pop()
                    if "user-agent" in v_headers:
                        user_agent = v_headers["user-agent"]
    if api_key is None:
        raise NoValidHarFileError("No access token found in .har files")

    return api_key, user_agent


async def get_access_token_and_user_agent(url: str, proxy: str = None):
    browser, stop_browser = await get_nodriver(proxy=proxy, user_data_dir="designer")
    try:
        page = await browser.get(url)
        user_agent = await page.evaluate("navigator.userAgent", return_by_value=True)
        access_token = None
        while access_token is None:
            access_token = await page.evaluate(
                """
                (() => {
                    for (var i = 0; i < localStorage.length; i++) {
                        try {
                            item = JSON.parse(localStorage.getItem(localStorage.key(i)));
                            if (item.credentialType == "AccessToken" 

View on GitHub (pinned to 973504e177)

Solutions

  1. Re-export the HAR: log into the Designer/Bing Image Creator site first, then record the session and export the .har file
  2. Confirm the HAR contains a request to the designer URL with an Authorization: Bearer ... header (search the JSON for 'authorization')
  3. Place the .har file where g4f looks (get_har_files() paths) and ensure it is valid JSON
  4. Alternatively rely on the nodriver flow get_access_token_and_user_agent() which reads the token from browser localStorage instead of HAR

Example fix

# before
# HAR exported while logged out -> NoValidHarFileError

# after
# 1. open Chrome, sign in at the designer site
# 2. DevTools -> Network -> record -> refresh page -> export HAR
# 3. save to the g4f HAR directory, then:
api_key, user_agent = readHAR(designer_url)
Defensive patterns

Strategy: validation

Validate before calling

import json
def har_has_designer_token(path: str, url_prefix: str) -> bool:
    try:
        har = json.load(open(path, 'rb'))
    except (json.JSONDecodeError, OSError):
        return False
    return any(
        e['request']['url'].startswith(url_prefix)
        and any(h[0].lower() == 'authorization' for h in [(k, v) for k, v in e['request'].get('headers', {}).items()])
        for e in har.get('log', {}).get('entries', [])
    )

Type guard

def har_contains_auth(har: dict, url_prefix: str) -> bool:
    for e in har.get('log', {}).get('entries', []):
        if e.get('request', {}).get('url', '').startswith(url_prefix):
            headers = {k.lower(): v for k, v in e['request'].get('headers', {}).items()}
            if 'authorization' in headers:
                return True
    return False

Try / catch

from g4f.errors import NoValidHarFileError
try:
    api_key, ua = readHAR(designer_url)
except NoValidHarFileError:
    api_key, ua = await get_access_token_and_user_agent(designer_url, proxy)  # nodriver fallback

Prevention

When it happens

Trigger: readHAR(url) runs (via _create_auth_from_har or similar) and every HAR file either fails JSON parsing, contains no matching URL entries, or matching entries lack an authorization header.

Common situations: HAR exported before signing into designer services so no auth header was captured; wrong URL prefix captured (different Microsoft endpoint); HAR files missing from the expected directory; expired token not the issue here — none was found at all.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/18f62dcea8ca18fb. Report an issue: GitHub.