Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...