Stuck with Python HTTP Server with Basic Authentication using BaseHTTP

前端 未结 2 1669
深忆病人
深忆病人 2020-12-13 16:21

I am stuck trying to get a python based webserver to work.

I want to do Basic Authentication (sending a 401 header) and authenticating against a list of users. I hav

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 16:55

    Try this for size:

    import SimpleHTTPServer
    import SocketServer
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
    
    class Handler(BaseHTTPRequestHandler):
        ''' Main class to present webpages and authentication. '''
        def do_HEAD(self):
            print "send header"
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
    
        def do_AUTHHEAD(self):
            print "send header"
            self.send_response(401)
            self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
            self.send_header('Content-type', 'text/html')
            self.end_headers()
    
        def do_GET(self):
            ''' Present frontpage with user authentication. '''
            if self.headers.getheader('Authorization') == None:
                self.do_AUTHHEAD()
                self.wfile.write('no auth header received')
                pass
            elif self.headers.getheader('Authorization') == 'Basic dGVzdDp0ZXN0':
                self.do_HEAD()
                self.wfile.write(self.headers.getheader('Authorization'))
                self.wfile.write('authenticated!')
                pass
            else:
                self.do_AUTHHEAD()
                self.wfile.write(self.headers.getheader('Authorization'))
                self.wfile.write('not authenticated')
                pass
    
    httpd = SocketServer.TCPServer(("", 10001), Handler)
    
    httpd.serve_forever()
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题