Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js / Angular.js Admin authorized routes

I'm working on a MEAN application with authentication using JSON web tokens. basically on every request, I am checking to see if user has a valid token. if so they can go through to the route, otherwise they are returned to login page.

I want to make certain routes /admin/etc... only accessible to logged in users who are also admin. I have set up an isAdmin flag in mongo. I am new to nodejs and wondering what is the best way to check this. Do I do it on the angular side in routes? Or can I somehow create permission-based tokens on authentication? For reference, I am following the code from the MEAN Machine book, in particular here -

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

like image 452
user2994560 Avatar asked May 08 '15 18:05

user2994560


1 Answers

First, authorization decisions must be done on the server side. Doing it on the client side in Angular.js as you suggested is also a good idea, but this is only for the purpose of improving the user's experience, for example not showing the user a link to something they don't have access to.

With JWTs, you can embed claims about the user inside the token, like this:

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

To map permissions to express routes, you can use connect-roles to build clean and readable authorization middleware functions. Suppose for example your JWT is sent in the HTTP header and you have the following (naive) authorization middleware:

// Naive authentication middleware, just for demonstration
// Assumes you're issuing JWTs somehow and the client is including them in headers
// Like 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, you can enforce your authorization policy on routes, like 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 that there are much better options for issuing & validating JWTs, like express-jwt, or using passport in conjunction with passort-jwt

like image 142
Andrew Lavers Avatar answered Nov 04 '22 02:11

Andrew Lavers