2014-10-18 88 views
2

我使用Node.js構建了一個API,並且我有一些我想保護的端點。使用Passport基於動態路由進行身份驗證

爲簡單起見,我們假設我爲所有終端使用HTTP基本身份驗證(passport-http)。

我想要做的就是確保這樣的路線:api.example.com/users/:uid/只能由具有該ID的用戶訪問。

我可以像這樣做:

app.get('/users/:uid', 

    passport.authenticate('basic', { 
     session: false 
    }), 

    function (req, res, next) { 
     if (req.params.uid !== user.id) { 
      return next(new Error('Unauthorized')); 
     } 
     return next(); 
    }, 

    function (req, res, next) { 
     // do secret stuff 
    } 

); 

但我不知道是否有辦法做到這一點無需增加額外的中間件,通過使用Passport本身:

app.get('/users/:uid', 

    passport.authenticate(???), 

    function (req, res, next) { 
     // do secret stuff 
    } 

); 

是否有可能?如果不是,還有更好的方法嗎?

回答

2

你可以嘗試這樣的事情。一般說明:對所有在/ users路徑下的任何請求進行身份驗證的請求進行身份驗證。在您的特定路線上,使用一些中間件,確保嘗試訪問特定路線的用戶通過uid路線本身。

function authorizeUser(req, res, next) { 
    if (req.user.uid !== req.params.uid) next(new Error('Not your profile!')); 
    next(); 
} 

// Require login for entire /users section 
app.use('/users', passport.authenticate('basic', { session: false })); 

// Authorize /users/:uid section to one user 
app.use('/users/:uid', authorizeUser); 

// Nested routes will all be secured by the middleware above. 
app.get('/users/:uid', function (req, res) { 
    // Secret stuff 
}); 
app.get('/users/:uid/foo/bar', function (req, res) { 
    // Also secret 
}); 

如果您只保護一個端點,則可以將它全部放在同一條路徑上。

相關問題