create a http server and parse authorization headers in python

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.py
import http.server
import base64
import re

class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        auth_header = self.headers.get('Authorization')
        if auth_header:
            auth_header = re.sub('^Basic ', '', auth_header)
            user_pass = base64.b64decode(auth_header).decode("utf-8").split(":")
            print("Username:", user_pass[0])
            print("Password:", user_pass[1])
        else:
            print("No authorization header found.")
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Hello, World!')

if __name__ == '__main__':
    httpd = http.server.HTTPServer(('localhost', 8000), MyHTTPRequestHandler)
    httpd.serve_forever()
742 chars
22 lines

In 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.py
python server.py
17 chars
2 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