2014-10-10 95 views
2

我想阻止用戶直接輸入頁面的URL並引導到頁面。 如何在節點中實現此功能? 我知道,在Web應用程序中將文件放置在WEB-INF文件夾下會阻止直接訪問它們。防止直接訪問節點js中的html頁面

+0

您可以檢查引薦者,但刮板可以很容易地繞過。儘管如此,普通人會被阻擋。在你做這件事之前想一想。它可能導致可用性問題。 – Paul 2014-10-10 06:44:46

回答

1

如果您正在使用Express您可以在中間件檢查引用者有這樣的事情,它需要你的確切目的,您應該進一步適應:

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 

測試(與對策)

我們能否獲取主頁?

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’ 

我們能直接拿到第二頁? 沒有

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. 

我們能否從第一頁獲得的第二頁?

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’ 

可以在任何腳本小子學會使用wget --referer戰勝這種「保護」方案?

是的。它只會阻止誠實的人。不是真的想要內容的人。