我已經創建了使用快速框架的節點js應用程序。基於快速JS路由的身份驗證
我創建了中間件來限制對某些路線的訪問。
中間件實際上正常工作。但我在顯示數據時遇到困難。
假設在我的應用程序中,我創建了顯示國家('/ country/master')列表的路線,例如使用內部不同/默認路徑('/ country /')的html頁面從mongoDB獲取數據。
在這種情況下,用戶將無法看到數據,因爲我沒有給予「/」路由權限。但我想顯示數據但不允許他使用「/」路徑來檢查數據。
我該如何處理這種情況?
我已經創建了使用快速框架的節點js應用程序。基於快速JS路由的身份驗證
我創建了中間件來限制對某些路線的訪問。
中間件實際上正常工作。但我在顯示數據時遇到困難。
假設在我的應用程序中,我創建了顯示國家('/ country/master')列表的路線,例如使用內部不同/默認路徑('/ country /')的html頁面從mongoDB獲取數據。
在這種情況下,用戶將無法看到數據,因爲我沒有給予「/」路由權限。但我想顯示數據但不允許他使用「/」路徑來檢查數據。
我該如何處理這種情況?
問題的答案取決於你的身份驗證策略,即您使用的會話標識符,訪問令牌等
在這兩種情況下,我建議你打破認證中的憑證交換(aka登錄)。它們應該是單獨的中間件功能。下面是這個樣子的例子。
雖然這回答了您的問題,特定於ExpressJS,但您在構建身份驗證系統時(例如如何安全存儲密碼)會遺漏掉很多其他詳細信息。我在Stormpath工作,我們提供用戶管理作爲API,以便您不必擔心所有安全細節!使用express-stormpath模塊將我們的API集成到您的應用程序中非常簡單。您將在幾分鐘內擁有全功能的用戶數據庫,而無需設置mongo或用戶表。
所有這一切說,這裏的例子:
/* pseudo example of building your own authentication middleware */
function usernamePasswordExchange(req,res,next){
var username = req.body.username;
var password = req.body.password;
callToAuthService(username,password,function(err,user){
if(err){
next(err); // bad password, user doesn’t exist, etc
}else{
/*
this part depends on your application. do you use
sessions or access tokens? you need to send the user
something that they can use for authentication on
subsequent requests
*/
res.end(/* send something */);
}
});
}
function authenticate(req,res,next){
/*
read the cookie, access token, etc.
verify that it is legit and then find
the user that it’s associated with
*/
validateRequestAndGetUser(req,function(err,user){
if(err){
next(err); // session expired, tampered, revoked
}else{
req.user = user;
next();
}
});
}
app.post('/login',usernamePasswordExchange);
app.get('/protected-resource',authenticate,function(req,res,next){
/*
If we are here we know the user is authenticated and we
can know who the user is by referencing req.user
*/
});
你可以在你app.for例如定位中間件: -
app.get('/country/master',function(req,res){
})
app.use(function(req,res){
your middle ware for providing authentication
})
// other routes where authentication should be enabled
app.get('other urls')
我有路由「/ country/master」,這是我的html視圖,「/ country /」是默認的api獲取數據。這是我的應用程序獲取數據所需的,我需要當用戶試圖擊中瀏覽器上面的網址時,他應該受到限制 – Overseas634
@ Overseas634你試圖說/ country/master是路由,它給出了html頁面作爲響應。 – KlwntSingh
yes'/ country/master'是給出html頁面作爲迴應的路由 – Overseas634
你是什麼化妝用的是什麼意思?如果你的意思是你想禁止某人發佈數據,那麼你只能使用中間件進行發佈。 like ...'app.post('/',yourRestrictionFunction)' – Pravin