一 首先使用flask 编写一个Web服务器,用于模拟基础验证页面。代码如下。
from flask import Flask
from flask import request
import base64
app = Flask(__name__)
def hasAuth(auth,response):
if auth == None or auth.strip() == "":
response.status_code = 401
response.headers['WWW-Authenticate'] = 'Basic realm = "localhost"'
return False
return True
@app.route("/")
def index():
response = app.make_response('username or pwd error')
print(request.headers)
auth = request.headers.get('Authorization')
print('Authorization:',auth)
if hasAuth(auth,response):
auth = str(base64.b64decode(auth.split(' ')[1]),'utf-8')
values = auth.split(':')
username = values[0]
passwd = values[1]
print('username:',username)
print('passwd:',passwd)
if username == 'Mary' and passwd == '1234':
return 'success'
return response
if __name__ == '__main__':
app.run()
运行结果如下图所示:此时访问
http://127.0.0.1:5000/
会出现用户名和密码的登陆框。
二 使用Authorization设置用户名和密码发送给服务端
from urllib import request, response
import base64
url = 'http://localhost:5000'
headers = {
'User-Agent':'Mozilla/5.0 (Macinosh; Intel Mac OS X 10_14_3) AppleWeKit/537.36'
'(KHTML, like Gecko) Chrom/72.0.3626.109 Safari/537.36',
'Host':'localhost:5000',
'Authorization':'Basic' + str(base64.b64encode(bytes('Mary:1234','utf-8')),'utf-8')
}
req = request.Request(url=url,headers=headers,method='GET')
reponse = request.urlopen(req)
print(response.read().decode('utf-8'))
这段代码报错500,但是http://localhost:5000' 可以访问,暂时没有找到原因(哭。
三 使用build_opener访问网页。
#!/usr/bin/env python3
#-*-coding=utf-8-*-
__author__='km'
from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener
from urllib.error import URLError
username = 'Mary'
password = '1234'
url = 'http://localhost:5000/'
p = HTTPPasswordMgrWithDefaultRealm()
p.add_password('localhost',url,username,password)
auth_header = HTTPBasicAuthHandler(p)
opener = build_opener(auth_header)
result = opener.open(url)
html = result.read().decode('utf-9')
print(html)
运行结果如下图:报错401,怀疑是realm原因,经过调试发现走到的是服务器第一个if语句里。暂时没有找到原因(哭。