Skip to content

LocalWebserver stuck if some other application is running on windows #378

@Teut2711

Description

@Teut2711

Hi,

When something is already running on port 8080, calling:

gauth.LocalWebserverAuth()
successfully opens the browser for OAuth, but after granting access, the redirect to http://localhost:8080/?code=... fails with ERR_CONNECTION_REFUSED.
The command line then just waits indefinitely for the code, because the local server never started on that port.

This happens because LocalWebserverAuth tries to bind to 8080 without checking if it’s free.

Proposed fix:
Check if the port is available before binding, and try alternatives in a small range (e.g., 8080–8085) before raising an error. Example using portpicker:

import portpicker

candidate_ports = [8080] + list(range(8081, 8086))
port_number = None
for p in candidate_ports:
    if portpicker.is_port_free(p):
        port_number = p
        break

if port_number is None:
    raise RuntimeError("No free port in range 8080–8085")

print(f"Using port {port_number}")

If a non-default port is selected, it would also need to be reflected in the OAuth URL so the redirect URI matches.
Users can pre-register multiple redirect URIs in Google Cloud Console to cover the fallback ports.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions