'node.js express-unless exclude a path from middleware.auth
I am looking to use express-unless to exclude a /health path from using middleware.auth. I am having syntax issues, and I am unable to test this locally. If I use localSite ==true, it will not work with my environment. The logs for the snytax is below. Any help or feedback would be appreciated.
I have tried,
app.use(middleware.auth.unless({ path: ['/health']}));
and other combinations, and I continue to get syntax issues.
Below is just a snippet of my code, that has what would be relevant to the middleware auth and the health path. var middleware = require('./middleware/middleware'); var cookieParser = require('cookie-parser'); // Enables us to read the cookies from the request headers
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();
});
Here is the logs from when I deploy this in bamboo which runs the node server.js which is my application.
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)
Here is my middleware.js which I am importing.
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);
}
}
});
}
}
}
};
Solution 1:[1]
As per the Usage notes, You need to add the below snippet like this, (you can add this after your var request = require('request');
statement)
middleware.auth.unless = unless;
Hope this helps!
Solution 2:[2]
Using express v4 at the time of this answer, place routes you don't want the middleware to intercept before using the middleware, like so:
app.get('/route1', (req, res) => res.send('Route without middleware'));
app.use(yourMiddleware());
app.get('/route2', (req, res) => res.send('Route with middleware'));
Edit:
You can still choose to run middleware any time in the endpoints defined before middleware by using the next() native middleware provided by express, like so:
app.get('/route1', (req, res, next) => {
console.log('Middleware not executed');
next(); // This runs yourMiddleware() and executes any code defined further in THIS endpoint
console.log('Middleware executed');
res.send('Weird endpoint...');
});
app.use(yourMiddleware());
app.get('/route2', (req, res) => res.send('Route with middleware'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |