2012-09-05 80 views
19

我正在使用最新版本的NodeJS和ExpressJS(用於MVC)。NodeJS + Express:如何保護URL

我通常配置我休息的路徑是這樣,例如:

app.get('/archive', routes.archive); 

現在我想我的/admin/*組URL被固定,我的意思是我需要的只是簡單的認證,它只是一個草案。

當用戶試圖訪問,例如/admin/posts,在發送相應的視圖和數據之前,我檢查req.session.authenticated。如果沒有定義,我重定向到登錄頁面。

登錄頁面有一個簡單的驗證形式,以及登錄在控制器的方法:如果用戶不發送「正確的用戶」和「正確的密碼」我設置會話變量,將他的認證。

我覺得困難或者我不明白的是,如何在每個/ admin/*路徑調用之前實際製作「過濾器」代碼,我的意思是auth檢查。

這是否與「中間件」表達功能有關?

謝謝

回答

59

是的,中間件正是你想要的。中間件功能就像其他任何Express路由處理程序一樣工作,它會在您的實際路由處理程序之前運行。你可以,例如,做這樣的事情:

function requireLogin(req, res, next) { 
    if (req.session.loggedIn) { 
    next(); // allow the next route to run 
    } else { 
    // require the user to log in 
    res.redirect("/login"); // or render a form, etc. 
    } 
} 

// Automatically apply the `requireLogin` middleware to all 
// routes starting with `/admin` 
app.all("/admin/*", requireLogin, function(req, res, next) { 
    next(); // if the middleware allowed us to get here, 
      // just move on to the next route handler 
}); 

app.get("/admin/posts", function(req, res) { 
    // if we got here, the `app.all` call above has already 
    // ensured that the user is logged in 
}); 

您可以指定requireLogin作爲中間件要被保護的,而不是使用app.all電話與/admin/*路線的每個,做起來我在這裏展示的方式確保您不會意外忘記將其添加到以/admin開頭的任何頁面。

+1

wow .... so StackOverflow有時候工作! :D ehehe謝謝,這正是我期望的答案。我會在下午嘗試,如果一切正常,請接受你的出色答案。 THX再次 –

+0

很高興幫助!如果您對此問題有任何疑問,請告訴我們!^_^ –

+0

使用令牌有什麼區別? –

1

像布蘭登,但你也可以去connect路線

app.use('/admin', requireLogin) 
app.use(app.router) 

app.get('/admin/posts', /* middleware */) 
+3

你是什麼意思? : - \ –

1

一個更簡單的方法是在App.js文件中添加以下代碼。

var auth = function(req, res, next) { 

    if(isAdmin) { 

     return next(); 

    } else { 

     return res.status(400) 

    } 
}; 

app.use('/admin', auth, apiDecrement); 

正如您所看到的,中間件正在連接到路由。在ExpressJS前進之前,它會執行您作爲第二個參數傳遞的函數。

有了這個解決方案,您可以顯示該網站最終用戶之前做不同的檢查。

最好。