Skip to content
wulin edited this page Jul 17, 2016 · 1 revision

Basic Auth

1.如它的名字,是基础的验证,所以会比较简单
2.会直接把用户名、密码的信息放在请求的 Header 中
3.携带信息的时候是把用户名、密码简单的拼接 & base64 掉,主要是为了解决账号、密码中可能存在的编码问题

安装

$ npm install basic-auth

API

var auth = require('basic-auth');
var user = auth(req);
// => { name: 'something', pass: 'whatever' }

###本课程的basic auth验证 我们将合法的帐号保存在config/authConfig.js中

var auth = require('basic-auth');
var authList = require('../config/authConfig');

module.exports = function(req, res, next) {
	var credentials = auth(req);

	if (!credentials || !authList[credentials.name] || credentials.pass != authList[credentials.name]) {
	    res.statusCode = 401;
	    res.setHeader('WWW-Authenticate', 'Basic realm="example"');
	    res.end('Access denied');
	} else {
	    next();
	}
}	

###在server.js中引入basic-auth中间件

app.use(require('./middlewares/basicAuth'));
// => 每个请求都会被拦载

Clone this wiki locally