1. 程式人生 > >HTTP基本認證(Basic Authentication) 實踐

HTTP基本認證(Basic Authentication) 實踐

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