I am serving a PDF file on node server at this path – /content/assets/sample.pdf. I want to restrict unauthorize access to this PDF file. For that, I have applied the authentication to /content/assets/*
router.use('/content/assets/*', isAuthenticated, (req, res) => {
const filePath = path.join(__dirname, '../../static', req.path);
console.log(filePath);
res.sendFile(filePath);
});
function isAuthenticated(req, res, next) {
const userIsAuthenticated = true;
if (userIsAuthenticated) {
next();
} else {
res.status(403).send('Unauthorized');
}
}
When I try postman to check this, I am able to restrict /content/assets/ but not /content/assets/sample.pdf
Is there anything I can do to restrict the PDF file ?
2
Answers
You should use
app.all
instead ofapp.use
. Why? Because theuse
function in Express middleware checks only for the pathcontent/assets
, soreq.path
in the case ofapp.use
will be justcontent/assets
but never the file path included. This might be confusing, butapp.all
ensures that the middleware applies to all HTTP methods and properly captures the file path.( bit confusing right ?! )Anyways if you use the
app.all
then it registers a middleware function that will be executed for all HTTP methods (GET, POST, PUT, DELETE, etc.) at the specified route pattern. It matches all HTTP methodscommonly used for route-wide configurations or error handling
.Solution :
Read more about app.use vs app.all
Actually, there are two problems here:
The first problem here is that the file is located in your
static
directory, which you made public using some code likeThe static middleware without any restriction already makes your file public for all types of access. To limit its access, you can do it either way:
The second problem is using using a wildcard along with
app.use()
. Theapp.use()
method by default matches the prefix of the URL, so no need to add a wildcard path here.