【问题标题】:Make route endpoint respond with different content based on user authentication使路由端点根据用户身份验证以不同的内容响应
【发布时间】:2016-04-11 08:21:21
【问题描述】:

假设我正在构建一个带有 REST 后端的简单 Web 应用程序,用户在其中拥有自己的包含用户信息的页面。

我想要实现的是,如果未经身份验证的用户向

www.mywebapp.com/api/user/john

他们将获得有限的信息(例如只有年龄和电子邮件)。但是如果用户登录并发出相同的请求,服务器也会响应更多信息(如个人偏好等)。

我在想可能是验证用户令牌的中间件传递请求的权限(req.role = guest 或 req.role = user)。然后在 user/:name 端点中,它会检查角色并以不同的内容进行响应。

另一种选择是为经过身份验证的用户创建一个新的路由端点,然后检查在客户端调用哪个端点。

这里的最佳做法是什么?

【问题讨论】:

  • 选择中间件。许多广泛使用的身份验证模块(如passportjs)都使用这种模式。
  • 我使用护照进行用户身份验证。要检查用户是否登录,我检查 req.session.passport.user 是否存在。如果确实存在,我然后使用该变量查询数据库以查看登录用户的用户类型(管理员、常规等)。我根据从数据库返回的用户类型提供适当的内容

标签: node.js express


【解决方案1】:

这就是我最终的做法:

let router = express.Router();

router.get('/profile', authenticate, hasRole("Admin", true), controller.showProfileAdmin);
router.get('/profile', hasRole("User", true), controller.showProfileUser);
// will not call next('route') if Guest requirements is not met
router.get('/profile', hasRole("Guest"), controller.showProfile); 

// hasRole() returns a middleware function that checks if user meets role requirement.
// If nextRoute is true, the function calls next('route'). If nextRoute is false
// or undefined, the function responds with a 403
function hasRole(roleRequired, nextRoute) {

    return (req, res, next) => {
        // Just checking so that the user has authority for this role.
        if (config.userRoles.indexOf(req.user.role) >= config.userRoles.indexOf(roleRequired)) {
            return next();
        //else client is not authorized
        } else {
            // If nextRoute is true, continue to the next route.
            if(nextRoute){
                return next('route');
            //Else respond with a forbidden status.
            } else {
                res.sendStatus(403);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-01-06
    • 2017-08-26
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多