Node.js / Angular.js Admin authorized routes

后端 未结 1 736
渐次进展
渐次进展 2020-12-20 21:45

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 t

相关标签:
1条回答
  • 2020-12-20 22:13

    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

    0 讨论(0)
提交回复
热议问题