Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I protect an API endpoint with PassportJS?

My app use Express and AngularJS. I'm using express to handle basic web seving of the angular code via static. The angular code uses services that hit API endpoints hosted by express. I only want the API endpoints to be accessible after a user has authenticated. How can I accomplish this via PassportJS?

like image 679
Shamoon Avatar asked Nov 15 '13 11:11

Shamoon


1 Answers

I have uploaded an Angular-Express project on github that I have been working on.

It is still work in progress. I hope it helps.

It uses PassportJs for user authentication and is a basic example of server side authorization. It demonstrates how to make API calls accessible only to authenticated users, or only to users with admin role. This is achieved in server/routes.js calling the middleware functions ensureAuthenticated, and ensureAdmin which are defined in server/authentication.js

in routes.js

// anybody can access this 
app.get('/api/test/users', 
        api.testUsers);


// only logged-in users with ADMIN role can access this 
app.get('/api/users',          
        authentication.ensureAdmin,
        api.testUsers);

// only logged-in users can access this
app.get('/api/books', 
        authentication.ensureAuthenticated, 
        api.books);

in authentication.js

ensureAuthenticated: function(req, res, next) {
    if (req.isAuthenticated()) {
       return next();
    } else {
       return res.send(401);
    }
},

ensureAdmin: function(req, res, next) {
  // ensure authenticated user exists with admin role, 
  // otherwise send 401 response status
  if (req.user && req.user.role == 'ADMIN') {
      return next();
  } else {
      return res.send(401);
  }
},
like image 163
klode Avatar answered Oct 04 '22 05:10

klode