如何创建打开时弹出Windows Security对话框的测试网页
本地搭建触发Windows Security认证弹窗的测试页面方案
Edge弹出Windows Security对话框的核心逻辑是:Web服务端返回401 Unauthorized状态码,并携带WWW-Authenticate响应头要求客户端完成身份认证,浏览器识别到该响应就会调用系统级认证弹窗,和公司内网站点的触发逻辑完全一致,本地可以按以下方法快速搭建测试环境,无需依赖生产环境。
最快实现:基于Python内置模块搭建(无需额外安装Web服务)
- 新建本地测试目录,比如命名为
auth_test_site,在目录内创建测试页面index.html,写入需要模拟的页面元素,比如待点击的目标按钮,示例内容:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>内网测试模拟页</title> </head> <body> <h1>模拟内网业务页面</h1> <button id="submitBtn">指定待点击按钮</button> </body> </html>
- 在同目录下创建认证服务脚本
auth_server.py,逻辑为首次访问返回401认证要求触发弹窗,校验账号密码通过后返回测试页面:
from http.server import HTTPServer, BaseHTTPRequestHandler import base64 # 自定义测试用的账号密码,用于验证自动填充逻辑 VALID_USER = "test_account" VALID_PWD = "test_password" class AuthRequestHandler(BaseHTTPRequestHandler): def do_GET(self): # 检查请求是否携带认证凭证 auth_header = self.headers.get("Authorization") if not auth_header: # 返回401状态,携带认证头触发系统弹窗 self.send_response(401) # 同时声明NTLM和Basic认证,和公司内网常用的IIS认证行为完全匹配 self.send_header("WWW-Authenticate", "NTLM") self.send_header("WWW-Authenticate", 'Basic realm="Company Intranet"') self.end_headers() return # 校验Basic认证的账号密码(NTLM认证场景下弹窗触发逻辑一致,无需额外适配) if auth_header.startswith("Basic "): cred_part = auth_header.split(" ", 1)[1] decoded_cred = base64.b64decode(cred_part).decode("utf-8") input_user, input_pwd = decoded_cred.split(":", 1) if input_user != VALID_USER or input_pwd != VALID_PWD: self.send_response(401) self.send_header("WWW-Authenticate", "NTLM") self.send_header("WWW-Authenticate", 'Basic realm="Company Intranet"') self.end_headers() return # 认证通过,返回测试页面内容 self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.end_headers() with open("index.html", "rb") as f: self.wfile.write(f.read()) if __name__ == "__main__": # 服务绑定本地8000端口 server = HTTPServer(("127.0.0.1", 8000), AuthRequestHandler) print("测试服务已启动,访问地址:http://127.0.0.1:8000") server.serve_forever()
- 启动服务:在测试目录下执行命令
python auth_server.py,用Edge访问http://127.0.0.1:8000即可触发和内网一致的Windows Security认证弹窗,输入预设的测试账号密码即可进入测试页面,完全满足Autoit填充、Selenium点击按钮的全流程测试需求。
测试注意事项
- 访问时使用
127.0.0.1而非localhost,部分Edge版本会将localhost默认划入可信站点,自动透传系统凭证导致不弹出认证框。 - 如果测试时Edge自动填充了之前保存的凭证不弹框,可以打开Edge的InPrivate无痕窗口访问,或者清除127.0.0.1对应的站点缓存、凭证数据后再试。
- 如果需要更贴近内网的NTLM认证弹窗表现,不需要修改现有逻辑,响应头里的
NTLM声明已经可以让弹窗显示和内网完全一致的Windows安全中心样式。
轻量替代方案
如果本地已经安装了Nginx、IIS这类Web服务,直接给站点开启Basic认证或Windows集成认证即可,不需要写Python脚本,核心逻辑都是给响应加WWW-Authenticate头触发401认证流程,最终弹出的系统弹窗表现完全一致。
内容的提问来源于stack exchange,提问作者user2334659
相关产品推荐
相关产品推荐

