Angularjs,Expressjs和passportjs用于服务器端的身份验证检查

时间:2014-01-15 21:15:03

标签: javascript angularjs node.js express passport.js

我有一个Node.js应用程序,我在其中使用了Yeoman脚手架用于Angular。我也在服务器端使用ExpressJS。

基本上我的app结构是:

app
  -->views
      --> more files
server.js

结构比这更重,但这是为了保持简单。

基本上我在服务器端使用PassportJS进行身份验证。目前正在通过AngularJS路由参数执行路由。

我现在遇到了一个问题,因为我需要使用中间件方法进行身份验证:

function ensureAuthenticated(req, res, next) {
    console.log('authenticate=' + req.isAuthenticated());
    if (req.isAuthenticated()) { 
        return next(); 
    }
    res.redirect('/')
}

我在服务器端创建了一个app.get来检查用户是否在没有登录的情况下尝试访问管理页面:

app.get('/admin', ensureAuthenticated,
    function(req, res){
        console.log('get admin' + req.params);
        res.sendfile(__dirname + '/app/views/admin/users.html');
    });  

但它永远不会采用这种方法。我做错了什么?

任何建议都会很棒。

2 个答案:

答案 0 :(得分:1)

if (!req.isAuthenticated()) {
            return res.send(401, 'User is not authorized');
        }
        next();

答案 1 :(得分:0)

它无法工作的原因是因为在客户端配置路由时,angularjs locationprovider未设置为htmlmode5。添加了以下行:

$locationProvider.html5Mode(true);

这基本上删除了网址中的“#”。

相关问题