欢迎访问宙启技术站
智能推送

利用BaseHTTPRequestHandler处理HTTP身份验证的示例

发布时间:2023-12-24 07:25:16

以下是一个使用BaseHTTPRequestHandler处理HTTP身份验证的示例:

from http.server import BaseHTTPRequestHandler
import base64

# 定义用户名和密码
USERNAME = "admin"
PASSWORD = "password"

# 自定义处理请求的类
class AuthHandler(BaseHTTPRequestHandler):
    def do_AUTHHEAD(self):
        self.send_response(401)
        self.send_header('WWW-Authenticate', 'Basic realm="Authentication required"')
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        # 获取Authorization header
        auth_header = self.headers.get('Authorization')

        # 检查Authorization header是否存在且为Basic认证方式
        if auth_header is None or not auth_header.startswith('Basic '):
            self.do_AUTHHEAD()
            self.wfile.write(b'Unauthorized')
            return

        # 解码Authorization header中的用户名和密码
        auth_decoded = base64.b64decode(auth_header[6:]).decode('utf-8')
        username, password = auth_decoded.split(':')

        # 检查用户名和密码是否正确
        if username == USERNAME and password == PASSWORD:
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b'Authorized')
        else:
            self.do_AUTHHEAD()
            self.wfile.write(b'Unauthorized')

# 启动服务器
if __name__ == '__main__':
    from http.server import HTTPServer
    server = HTTPServer(('localhost', 8000), AuthHandler)
    print('Starting server at http://localhost:8000')
    server.serve_forever()

上述代码创建了一个自定义的HTTP请求处理类AuthHandler,该类继承自BaseHTTPRequestHandler。在该类中,do_GET方法用于处理GET请求,首先检查请求中是否包含合法的Authorization header,并对其进行解码。然后,将解码后的用户名和密码与预先定义的用户名和密码进行比较。如果匹配成功,返回200表示授权通过;否则,返回401表示授权失败。

最后,通过创建HTTPServer并将AuthHandler作为处理请求的类,可以启动一个监听在本地8000端口的HTTP服务器。当请求到达时,AuthHandler会自动调用do_GET方法来处理该请求,并进行身份验证。

使用时,可以通过发送带有Authorization header的HTTP请求来测试身份验证。例如,使用curl命令发送带有用户名和密码的GET请求:

curl -u admin:password http://localhost:8000

此时,将返回"Authorized"表示授权通过。如果修改用户名或密码,或者不传递Authorization header,则返回"Unauthorized"表示授权失败。