Is there a way to restrict allowed uri characters in Expressjs. like set a variable of characters:
allowed_uri_chars = 'a-zA-Z0-9'; etc
The most logical and easiest way to go would be to use a regex in some middleware:
var url = require("url");
app.use(function(req, res, next) {
var pathname = url.parse(req.url).pathname;
if(!pathname.match(/^[a-z0-9\/]+$/i)) return res.send(403);
next();
});
Or, as the URL is already parsed by Express, but this is not exposed publicly, you may want to save one call to parse and rely on Express internals (which I wouldn't advise):
app.use(function(req, res, next) {
if(!req._parsedUrl.pathname.match(/^[a-z0-9\/]+$/i)) return res.send(403);
next();
});
This ensures that your pathname (for http://example.com/foo/bar?id=1334
, pathname would be /foo/bar
) only contains letters, numbers, and slashes. It raises a 403 if not.
Can't you use a regex to parse the authorized chars?
Or do you mean in the routing directly?