简体   繁体   中英

Angularjs, Expressjs and passportjs for authentication checks on server side

I have a Node.js application where I have used Yeoman scaffolding for Angular. I am also using ExpressJS for server side.

So basically my app structure is:

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

The structure is more heavy than this, but this is to keep it simple.

Basically I have used PassportJS on the server side for authentication. The routing is currently being carried out via AngularJS routing parameters.

I have come across an issue now as I need to carry out authentication by using a middleware method:

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

I have created an app.get on the server side to check if the user tries to get to the admin page without logging in:

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

But it never goes to the method. What am I doing wrong?

Any advice would be great.

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

The reason it was not working was because angularjs locationprovider was not set to htmlmode5 when configuring the routes on the client side. The following line was added:

$locationProvider.html5Mode(true);

This basically removes the '#' from the url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM