Reputation: 7768
I would like to prevent the user from directly typing in the url of the page and getting led to the page. How can I achieve this functionality in node ? I know that in web applications placing the files under the WEB-INF folder prevent direct access to them.
Upvotes: 2
Views: 3320
Reputation: 27423
If you are using Express
you can check referer in middleware with something like this, which you should adapt further as needed for your exact purposes:
var express = require('express')
var app = express()
permittedLinker = ['localhost', '127.0.0.1']; // who can link here?
app.use(function(req, res, next) {
var i=0, notFound=1, referer=req.get('Referer');
if ((req.path==='/') || (req.path==='')) next(); // pass calls to '/' always
if (referer){
while ((i<permittedLinker.length) && notFound){
notFound= (referer.indexOf(permittedLinker[i])===-1);
i++;
}
}
if (notFound) {
res.status(403).send('Protected area. Please enter website via www.mysite.com');
} else {
next(); // access is permitted, go to the next step in the ordinary routing
}
});
app.get('/', function(req,res){
res.send('<p>Hello. You are at the main page. </p><a href="page2">page 2</a>');
});
app.get('/page2', function(req,res){
res.send('<p>You are at page 2</p>');
});
app.listen(3000); // test at http://localhost:3000
Can we get the main page? Yes
wget http://localhost:3000/
--2014-10-10 04:01:18-- http://localhost:3000/
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:3000... connected.
HTTP request sent, awaiting response...
200 OK
Length: 67 [text/html]
Saving to: ‘index.html’
Can we get the second page directly? No
wget http://localhost:3000/page2
--2014-10-10 04:04:34-- http://localhost:3000/page2
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:3000... connected.
HTTP request sent, awaiting response... 403 Forbidden
2014-10-10 04:04:34 ERROR 403: Forbidden.
Can we get the second page from the first page? Yes
wget --referer="http://localhost" http://localhost:3000/page2
--2014-10-10 04:05:32-- http://localhost:3000/page2
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:3000... connected.
HTTP request sent, awaiting response...
200 OK
Length: 24 [text/html]
Saving to: ‘page2’
Can any script kiddie learn to use wget --referer to defeat this "protection" scheme?
Yes. It only blocks honest people. Not someone who really wants the contents.
Upvotes: 1