2016-01-20 96 views
1

你好我有一個問題,防止用戶通過輸入網址來訪問我的網站。我有一個登錄,我想成爲訪問我的/factory/homepage.html頁面的唯一方法。 但是,如果用戶在URL字段中鍵入/factory/homepage.html,則可以訪問homepage.html。 我已經在使用app.get('/factory/'),但我的res.redirect('/website/userLogin.html')未重定向到登錄頁面。 這裏是我的代碼:如何防止用戶直接在node.js中訪問網頁?

app.get('/factory/*', function(req,res,next){ 
    console.log("going through app.get..."); 
    res.redirect('../website/userLogin.html'); 
    console.log('after redirect...'); 
}); 

輸出是:

going through app.get... 
after redirect... 

而且,用戶被引導到factory/homepage.html。我也試過app.use('/factory/*'),但沒有運氣。如果輸入了不中我廠目錄中的路徑,例如/factory/hello.html會重定向到/website/userLogin.html

我會喜歡的目錄/factory到無法通過在輸入網址訪問的轉向纔有效。然後,我將實施一箇中間件功能來檢查用戶是否通過身份驗證。

任何幫助將不勝感激!

+0

希望我不會誤解你..但我認爲解決方案是一個簡單的身份驗證問題。你可以設置一個app.get(index)並檢查請求是否通過了認證,如果沒有,重定向到其他頁面? – fzxt

+0

如果你正在檢查他們是否登錄,爲什麼他們訪問其他頁面之前的登錄頁面有什麼關係?爲什麼認證不夠? – Quentin

+0

可能相關:[CSRF](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) – Quentin

回答

0

我會嘗試這樣的事情。

app.get('/factory/*', function(req,res,next){ 

    var authenticated = false; 

    //do something to authenticate user 

    if(authenticated === true){ 
     //user is already authenticated 
     res.redirect('/factory/homepage.html'); 
    }else{ 
     //redirect to login 
     res.redirect('../website/userLogin.html'); 
    } 
}); 
+0

我嘗試了您的建議,並且仍然直接進入了/factory/homepage.html頁面。由於authenticated等於false,所以執行else代碼,但res.redirect不執行。 – HFernando

+0

如果用戶已通過身份驗證,請將'//執行一些操作來驗證用戶身份,以將'authenticated'更改爲'true'。 – Will