HTTP基本认证(Basic Authentication) 实践

2 篇文章 0 订阅
2 篇文章 0 订阅

服务端 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()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值