服务端 nodejs
var http = require('http')
var server = http.createServer()
server.listen(80, function () {
console.log('running...')
})
server.on('request', function (req, res) {
console.log(req.headers)
var auth = req.headers.authorization
if(auth){
// authorization: 'Basic Z3p3Omd6d3B3ZA=='
auth = auth.split(' ')[1]
authUser = new Buffer(auth,'base64').toString().split(':')
account = authUser[0]
password = authUser[1]
console.log(auth)
if(account === 'gzw' && password ==='gzwpwd'){
res.end('success')
}else{
res.end('Auth Faile.')
}
}
res.writeHead(401,{
'content-Type':'text/plain',
'WWW-Authenticate':'Basic realm="family"'
});
})
客户端 python
# -*- coding:utf-8 -*-
import urllib2
test = 'gzw'
pwd = 'gzwpwd'
webserver = '127.0.0.1'
# 构建一个密码管理对象,可以用来保存和HTTP请求相关的授权账户信息
passwordMgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# 添加授权账户信息,第一个参数realm如果没有指定就写None,后三个分别是站点IP,账户和密码
passwordMgr.add_password(None,webserver,test,pwd)
httpauth_handler = urllib2.HTTPBasicAuthHandler(passwordMgr)
opener = urllib2.build_opener(httpauth_handler)
request = urllib2.Request('http://'+webserver)
# 有授权验证信息的
response = opener.open(request)
# 没有授权验证信息的
# response = urllib2.urlopen(request)
print response.read()