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?
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);
}
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With