angularjs - Node.js / Angular.js Admin authorized routes -


i'm working on mean application authentication using json web tokens. on every request, checking see if user has valid token. if can go through route, otherwise returned login page.

i want make routes /admin/etc... accessible logged in users admin. have set isadmin flag in mongo. new nodejs , wondering best way check this. do on angular side in routes? or can somehow create permission-based tokens on authentication? reference, following code mean machine book, in particular here -

https://github.com/scotch-io/mean-machine-code/tree/master/17-user-crm

first, authorization decisions must done on server side. doing on client side in angular.js suggested idea, purpose of improving user's experience, example not showing user link don't have access to.

with jwts, can embed claims user inside token, this:

var jwt = require('jsonwebtoken'); var token = jwt.sign({ role: 'admin' }, 'your_secret'); 

to map permissions express routes, can use connect-roles build clean , readable authorization middleware functions. suppose example jwt sent in http header , have following (naive) authorization middleware:

// naive authentication middleware, demonstration // assumes you're issuing jwts somehow , client including them in headers // this: authorization: jwt {token} app.use(function(req, res, next) {     var token = req.headers.authorization.replace(/^jwt /, '');     jwt.verify(token, 'your_secret', function(err, decoded) {         if(err) {             next(err);         } else {             req.user = decoded;             next();         }     }); }) 

with that, can enforce authorization policy on routes, this:

var connectroles = require('connect-roles'); var user = new connectroles();  user.use('admin', function(req) {     return req.user && req.user.role === 'admin'; })  app.get('/admin', user.is('admin'), function(req, res, next) {     res.end(); }) 

note there better options issuing & validating jwts, express-jwt, or using passport in conjunction passort-jwt


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -