根据(我希望如此)接受的答案,我想将此代码作为所提出问题的结构解决方案提供。(您可以非常轻松地自定义它)。
// ------------------------------------------------------
// server.js
// .......................................................
// requires
var fs = require('fs');
var express = require('express');
var myBusinessLogic = require('../businessLogic/businessLogic.js');
// .......................................................
// security options
/*
1. Generate a self-signed certificate-key pair
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out certificate.pem
2. Import them to a keystore (some programs use a keystore)
keytool -importcert -file certificate.pem -keystore my.keystore
*/
var securityOptions = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('certificate.pem'),
requestCert: true
};
// .......................................................
// create the secure server (HTTPS)
var app = express();
var secureServer = require('https').createServer(securityOptions, app);
// ------------------------------------------------------
// helper functions for auth
// .............................................
// true if req == GET /login
function isGETLogin (req) {
if (req.path != "/login") { return false; }
if ( req.method != "GET" ) { return false; }
return true;
} // ()
// .............................................
// your auth policy here:
// true if req does have permissions
// (you may check here permissions and roles
// allowed to access the REST action depending
// on the URI being accessed)
function reqHasPermission (req) {
// decode req.accessToken, extract
// supposed fields there: userId:roleId:expiryTime
// and check them
// for the moment we do a very rigorous check
if (req.headers.accessToken != "you-are-welcome") {
return false;
}
return true;
} // ()
// ------------------------------------------------------
// install a function to transparently perform the auth check
// of incoming request, BEFORE they are actually invoked
app.use (function(req, res, next) {
if (! isGETLogin (req) ) {
if (! reqHasPermission (req) ){
res.writeHead(401); // unauthorized
res.end();
return; // don't call next()
}
} else {
console.log (" * is a login request ");
}
next(); // continue processing the request
});
// ------------------------------------------------------
// copy everything in the req body to req.body
app.use (function(req, res, next) {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
// ------------------------------------------------------
// REST requests
// ------------------------------------------------------
// .......................................................
// authenticating method
// GET /login?user=xxx&password=yyy
app.get('/login', function(req, res){
var user = req.query.user;
var password = req.query.password;
// rigorous auth check of user-passwrod
if (user != "foobar" || password != "1234") {
res.writeHead(403); // forbidden
} else {
// OK: create an access token with fields user, role and expiry time, hash it
// and put it on a response header field
res.setHeader ('accessToken', "you-are-welcome");
res.writeHead(200);
}
res.end();
});
// .......................................................
// "regular" methods (just an example)
// newBook()
// PUT /book
app.put('/book', function (req,res){
var bookData = JSON.parse (req.body);
myBusinessLogic.newBook(bookData, function (err) {
if (err) {
res.writeHead(409);
res.end();
return;
}
// no error:
res.writeHead(200);
res.end();
});
});
// .......................................................
// "main()"
secureServer.listen (8081);
这个服务器可以用 curl 测试:
echo "---- first: do login "
curl -v "https://localhost:8081/login?user=foobar&password=1234" --cacert certificate.pem
# now, in a real case, you should copy the accessToken received before, in the following request
echo "---- new book"
curl -X POST -d '{"id": "12341324", "author": "Herman Melville", "title": "Moby-Dick"}' "https://localhost:8081/book" --cacert certificate.pem --header "accessToken: you-are-welcome"