我为网站添加了Graphite,awstats的统计,所以就需要做一个页面,存放一些链接,以方便访问。但是这个页面不希望被其他人访问到,所以就需要做一些简单的验证--Basic Auth。
Nodejs的验证模块,比较有名的是connect-auth,不过这个太重量级的,所以我用的是很有针对性的,轻量级的认证模块,connect-basic-auth。这个模块只有一个源文件。。很简单。。
好,闲话少说。
1) 安装:npm install connect-basic-auth --save。
2) 从名字就可以看出,他是ExpressJs/ConnectJs的一个中间件,这是他的所有源代码:
module.exports = function (callback, realm) { if (!callback || typeof callback != 'function') { throw new Error('You must provide a function ' + 'callback as the first parameter'); } realm = realm ? realm : 'Authorization required.'; function unauthorized(res, sendResponse) { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"'); if (sendResponse) { res.end('Unauthorized'); } } return function(req, res, next) { req.requireAuthorization = function(req, res, next) { var authorization = req.headers.authorization; if (req.remoteUser) return next(); if (!authorization) return unauthorized(res, true); var parts = authorization.split(' '); var scheme = parts[0]; if ('Basic' != scheme) { return next(new Error('Authorization header ' + 'does not have the correct scheme. \'Basic\' ' + 'scheme was expected.')); } var _credentials = new Buffer(parts[1], 'base64').toString().split(':'); var credentials = { username: _credentials[0], password: _credentials[1] }; callback(credentials, req, res, function(err) { if (err) { unauthorized(res); next(err); return; } req.remoteUser = credentials.username; next(); }); }; next(); }; };
var should = require("should") , basicAuth = require('connect-basic-auth'); // Validate user's password exports.basicAuth = function () { return basicAuth(function (credentials, req, res, next) { if (credentials && credentials.username == "cer" && credentials.password == "site") { next(); } else { if (!credentials) console.log("credentials not provided"); if (credentials && credentials.username) console.log("credentials-username:" + credentials.username); if (credentials && credentials.password) console.log("credentials-password:" + credentials.username); next("Unautherized!"); } }); }
var express = require('express') , http = require('http') , path = require('path') , util = require('util') , middlewares = require('./middlewares'); var app = express(); app.configure(function () { app.set('env', 'production'); app.set('port', process.env.PORT || 80); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(middlewares.basicAuth()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.errorHandler()); });
var _ = require('underscore') , fs = require('fs') , spawn = require('child_process').spawn , util = require('util') , should = require('should') , async = require('async'); /////////////////////////// // Exports /////////////////////////// var g_app; exports.initRoutes = function (app) { g_app = app; var pageRequests = [ { method: "get", request: /^\/internal(\/.*)?/, handler: "auth" }, { method: "get", request: "/internal", handler: "index" }, { method: "get", request: "/internal/visisted_users", handler: "visistedUsers" }, { method: "get", request: "/internal/integration_test", handler: "integrationTest" }, ]; _.each(pageRequests, function (pageRequest) { var request, handler, method; request = pageRequest.request; handler = exports[pageRequest.handler]; method = app[pageRequest.method] || app.get; method.call(app, request, handler); }); } exports.auth = function (req, res, next) { req.requireAuthorization(req, res, next); } exports.index = function (req, res, next) { res.render("page_internal"); } exports.visistedUsers = function (req, res) { ...... } exports.integrationTest = function (req, res) { ...... }
-----------------------------------------
更新:因为iisnode托管,启用了域认证,所以basic auth不成功(当然不托管能行)