To create a HTTP server and parse authorization headers in Python, you can use the built-in http.server module along with the base64 and re modules.
Here's an example code:
main.py742 chars22 linesIn the code above, we define a custom HTTP request handler class MyHTTPRequestHandler that extends the BaseHTTPRequestHandler class. We override the do_GET() method to handle GET requests.
Inside the method, we first get the value of the Authorization header from the request headers. If the header is present, we extract the username and password from it using base64.b64decode and decode("utf-8"). We then remove the "Basic " prefix using re.sub.
If the header is not present, we simply print a message.
Finally, we send a HTTP response with a status code of 200 and write a "Hello, World!" message to the response body.
To run the server, simply save the code to a file (e.g. server.py) and run it using Python:
main.py17 chars2 lines
The server will then listen on localhost:8000 and print the username and password whenever a request with an Authorization header is received.
gistlibby LogSnag