Skip to content

Commit 3e8c309

Browse files
author
Mirko Vogt
committed
uaiohttpclient: Implement parsing and handling HTTP auth URLs
Allows HTTP Basic Auth URLs being passed, parsed and handled correctly to authorise against a server expecting that. This is a simplification, completely ignoring if the server supports or asks for HTTP Basic Auth. We simply format and set the header if the URL indicates so. This also fixes parsing URLs containing a colon (':') /not/ indicating a custom port (but e.g. the seperation between user and password as part of the HTTP Basic Auth credentials). Previously, the lib died ungracefully when parsing an URL containing HTTP Basic Auth credentials, as it was always expecting at most only one colon (':') and also the part coming afterwards being neccesarily a number (port).
1 parent 50ed36f commit 3e8c309

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

micropython/uaiohttpclient/uaiohttpclient.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -47,24 +47,28 @@ async def request_raw(method, url):
4747
proto, dummy, host = url.split("/", 2)
4848
path = ""
4949

50+
# Although we use HTTP protocol version 1.0, we still explicitly
51+
# set the header "Connection: close", even though this should be
52+
# default for 1.0, but some servers misbehave w/o it.
53+
hdrs = {'Connection': "close", 'User-Agent': "compat"}
54+
if "@" in host:
55+
# split off potential login creds from host
56+
auth, host = host.split("@", 1)
57+
from binascii import b2a_base64
58+
#usr, pwd = auth.split(":", 1)
59+
hdrs['Authorization'] = "Basic " + b2a_base64(auth).decode()
60+
5061
if ":" in host:
51-
host, port = host.split(":")
62+
host, port = host.rsplit(":", 1)
5263
port = int(port)
5364
else:
5465
port = 80
5566

5667
if proto != "http:":
5768
raise ValueError("Unsupported protocol: " + proto)
5869
reader, writer = await asyncio.open_connection(host, port)
59-
# Use protocol 1.0, because 1.1 always allows to use chunked
60-
# transfer-encoding But explicitly set Connection: close, even
61-
# though this should be default for 1.0, because some servers
62-
# misbehave w/o it.
63-
query = "%s /%s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\nUser-Agent: compat\r\n\r\n" % (
64-
method,
65-
path,
66-
host,
67-
)
70+
# Use protocol 1.0, because 1.1 always allows to use chunked transfer-encoding
71+
query = "%s /%s HTTP/1.0\r\nHost: %s\r\n%s\r\n\r\n" % (method, path, host, "\r\n".join("%s: %s" % (k,v) for k,v in hdrs.items()))
6872
await writer.awrite(query.encode("latin-1"))
6973
return reader
7074

0 commit comments

Comments
 (0)