本文介绍了Node.js / Angular.js管理授权路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用使用JSON网络令牌进行认证的MEAN应用程序。基本上每个请求,我正在检查用户是否有一个有效的令牌。如果是这样,他们可以通过路由,否则返回到登录页面。

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.

我想使某些路线/ admin / etc ...只能访问也是管理员的登录用户。我在mongo中设置了一个isAdmin标志。我是nodejs的新手,想知道什么是最好的方法来检查这个。我在路线上的角度做吗?或者我可以以某种方式在认证上创建基于权限的令牌?作为参考,我正在使用MEAN机器书中的代码,特别是在这里 -

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 -

推荐答案

首先,授权决定必须在服务器端完成。在您提出的Angular.js中,在客户端执行此操作也是一个好主意,但这只是为了改善用户的体验,例如不向用户显示无法访问的链接。

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.

使用JWT,您可以在令牌内嵌入用户声明,如下所示:

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');

要映射表达路由的权限,可以使用构建清晰可读的授权中间件功能。假设你的JWT是在HTTP头发送的,你有以下(天真的)授权中间件:

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();
        }
    });
})

路由授权策略如下:

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();
})

请注意,发行&验证JWT,例如,或使用与

Note that there are much better options for issuing & validating JWTs, like express-jwt, or using passport in conjunction with passort-jwt

这篇关于Node.js / Angular.js管理授权路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:24