-
-
Save tuket/a46f2f322a885ee5ede4206a76e6a597 to your computer and use it in GitHub Desktop.
SimpleAuthServer: A SimpleHTTPServer with authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Very simple HTTP server in python. | |
Usage:: | |
./dummy-web-server.py [<port>] | |
Send a GET request:: | |
curl http://localhost | |
Send a HEAD request:: | |
curl -I http://localhost | |
Send a POST request:: | |
curl -d "foo=bar&bin=baz" http://localhost | |
""" | |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
import SocketServer | |
import base64 | |
users = { \ | |
"user1" : "password1", | |
"user2" : "password2" | |
} | |
class S(BaseHTTPRequestHandler): | |
def _set_headers(self): | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
def do_GET(self): | |
auth = self.headers.getheader('Authorization') | |
if auth == None: | |
self.send_response(401) | |
self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"') | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
self.wfile.write('no auth header received') | |
else: | |
global users | |
splits = auth.split(' ') | |
ok = False | |
if len(splits) == 2 and splits[0] == 'Basic': | |
decoded = base64.b64decode(splits[1]) | |
up = decoded.split(':') | |
if len(up) == 2 and users.has_key(up[0]) and users[up[0]] == up[1]: | |
ok = True | |
if ok: | |
self._set_headers() | |
self.wfile.write("<html><body><h1>Welcome!</h1></body></html>") | |
else: | |
self.send_response(401) | |
self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"') | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
self.wfile.write('<html><body><h1>Nope</h1></body></html>') | |
def do_HEAD(self): | |
self._set_headers() | |
def do_POST(self): | |
# Doesn't do anything with posted data | |
self._set_headers() | |
self.wfile.write("<html><body><h1>POST!</h1></body></html>") | |
def run(server_class=HTTPServer, handler_class=S, port=80): | |
server_address = ('', port) | |
httpd = server_class(server_address, handler_class) | |
print 'Starting httpd...' | |
httpd.serve_forever() | |
if __name__ == "__main__": | |
from sys import argv | |
if len(argv) == 2: | |
run(port=int(argv[1])) | |
else: | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment