Я хочу использовать express - без исключения пути / health из файла middleware.auth. У меня проблемы с синтаксисом, и я не могу проверить это локально. Если я использую localSite == true, он не будет работать в моей среде. Журналы для snytax ниже. Буду признателен за любую помощь или обратную связь.
Я пробовал, app.use(middleware.auth.unless({ path: ['/health']}));
и другие комбинации, и я продолжаю получать проблемы с синтаксисом.
Ниже приведен лишь фрагмент моего кода, который имеет что будет иметь отношение к авторизации промежуточного программного обеспечения и пути работоспособности. var middleware = require ('./ middleware / middleware'); var cookieParser = require ('cook ie -parser'); // Позволяет нам читать куки-файлы из заголовков запросов
var middleware = require('./middleware/middleware');
var cookieParser = require('cookie-parser');
var unless = require('express-unless');
var express = require('express'),
//set an instance of express
app = express(),
//require the body-parser nodejs module
bodyParser = require('body-parser'),
//require the path nodejs module
path = require("path");
//const express = require('express');
var rp = require('request-promise');
var request = require('request');
if (localSite == false) {
//User cookieparser to validate user's cookie with middleware auth
app.use(cookieParser());
app.use(middleware.auth);
}
else {
userN = process.env.USERNAME;
userMail = process.env.userMail;
}
//healthcheck();
app.get('/health', function(req, res) {
console.log("online");
res.status(200).end();
});
Вот журналы, когда я развертываю это в бамбуке, который запускает сервер узла. js, который является моим приложением.
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]OUT middleware.js: THIS IS AUTH
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR app.use(middleware.auth.unless({ path: ['/health']}));
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]OUT middleware.js: node_env=development
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR /home/vcap/app/server.js:99
12-Feb-2020 11:04:18 2020-02-12T11:04.18-0500 [CELL/SSHD/0]OUT Exit status 0
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR ^
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR TypeError: middleware.auth.unless is not a function
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at Object.<anonymous> (/home/vcap/app/server.js:99:27)
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at Module._compile (internal/modules/cjs/loader.js:778:30)
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at Module.load (internal/modules/cjs/loader.js:653:32)
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at Function.Module._load (internal/modules/cjs/loader.js:585:3)
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at startup (internal/bootstrap/node.js:283:19)
12-Feb-2020 11:04:18 2020-02-12T11:04.17-0500 [APP/PROC/WEB/0]ERR at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
Вот мое промежуточное ПО. js, которое я импортирую.
var reactExpressMiddleware = require('react-express-middleware');
var jwt = require('jsonwebtoken'); // Use package for decoding/verifying JWTs
var jwkToPem = require('jwk-to-pem'); // Use JWK2PEM to convert from JWK sets into PEM keys
//var jwksClient = require('jwks-ec'); // Set up info for JWKS Client to reach out to JWKS server and grab appropriate PublicKeys
var cookieParser = require('cookie-parser'); // Enables us to read the cookies from the request headers
// const express = require('express');
var jwksClient = require('../dnaModule/jwks-ec');
var express = require('express'),
//set an instance of exress
app = express(),
//require the body-parser nodejs module
bodyParser = require('body-parser'),
//require the path nodejs module
path = require("path");
var node_env = process.env.NODE_ENV;
console.log("middleware.js: NODE ENV::::::::" + node_env);
if (node_env == "test") {
var jwks_url = 'https://test.com/pa/oidc/JWKS';
var cookie_name = 'PA.info';
}
const client = jwksClient({
cache: true,
cacheMaxEntries: 5, // Default value cacheMaxAge: '5h', // Default value
rateLimit: true,
jwksRequestsPerMinute: 10, // Default value
strictSsl: true, // Default value
jwksUri: jwks_url // Test Endpoint
});
notAuthorizedMsg = "Not authorized. You must belong to the auth group."
module.exports = {
auth: function (req, res, next) {
let decodedUser = null;
console.log('middleware.js: CHECK JWT!!!!!!!!!!');
// Check to see if JWT exists
if (typeof req.cookies[cookie_name] == "undefined") {
//send a 403 API access error
res.status(403).send(notAuthorizedMsg);
}
else {
console.log('middleware.js: NOT UNDEFINED!!!!!!!!!!');
//next();
// Get JWT and pull out the KID from request cookies
var token = req.cookies[cookie_name].toString();
var decoded = jwt.decode(token, {complete: true});
//console.log('middleware.js: token == ' + token);
//console.log('User_name == ' + user_name);
// Check for bogus token
if (decoded == null) {
res.status(403).send(notAuthorizedMsg);
}
else {
//console.log(typeof decoded.header);
var reloadRequest = false;
var kid = decoded.header.kid.toString();
console.log("middleware.js: KID ==" + kid);
// Retrieve signing public key
client.getSigningKey(kid, function (err, key) {
if (err) {
console.log("middleware.js: Error: ", err);
var reloadRequest = true;
//Reload the page if the key fetch fails, DNS will resolve.
//res.redirect('back');
}
else {
console.log('middleware.js: CONVERT KEY!!!!!!!!!');
const signingKey = key;
// Convert JWK to PEM for public key format
var cert = jwkToPem(signingKey);
// Verify the JWT against the public key
jwt.verify(token, cert, {algorithms: ['ES256']}, function (err, decodedToken) {
if (err) {
console.log('middleware.js: Error:', err.message);
var reloadRequest = true;
}
else {
console.log('middleware.js: DECODED!!!!!!!!!!');
//set req.user with the JWT fields from the decoded/verified token
//req.user = decodedToken;
//return next();
decodedUser = decodedToken;
}
});
}
if (reloadRequest) {
console.log('middleware.js: Attempting Reload of page');
res.redirect('back');
}
else if (decodedUser == null || typeof decodedUser === "undefined") {
console.log('middleware.js: Not Authorized, no valid decoded token found');
res.status(403).send(notAuthorizedMsg);
}
else if (typeof decodedUser.groups === "undefined") {
console.log('middleware.js: Not Authorized, no groups returned');
res.status(403).send(notAuthorizedMsg);
}
else {
//console.log('middleware.js: Groups are ' + decodedUser.groups);
// A single LDAP group is not returned in an Array whereas multiple are
// so we need to check before we do an includes check if we need
// to iterate over the groups list
let hasGroup = false;
if (decodedUser.groups instanceof Array) {
for (var i = 0; i < decodedUser.groups.length; i++) {
if (decodedUser.groups[i].includes('grouptest')) {
hasGroup=true;
break;
}
}
}
else {
hasGroup = decodedUser.groups.includes('grouptest');
}
if (hasGroup) {
res.cookie('sc_user', JSON.stringify({firstName}), {overwrite: true});
console.log('middleware.js: Name: ' + decodedUser.firstName + ' ' + decodedUser.lastName);
//console.log("middleware.js: All data: %o", decodedUser);
var nID = decodedUser.sub;
module.exports.first_name = decodedUser.firstName;
module.exports.last_name = decodedUser.lastName;
next();
}
else {
console.log('middleware.js: not authorized');
res.status(403).send(notAuthorizedMsg);
}
}
});
}
}
}
};