简体   繁体   English

保护Express和NodeJ上的路由

[英]Securing routes on Express and NodeJs

I'm looking the best way to "restrict" specific routes, I'm going to explain it with an example: 我正在寻找“限制”特定路线的最佳方法,我将通过一个示例进行说明:

I have two users: 我有两个用户:

-user1 id:123 -user1 ID:123

-user2 id:456 -user2 ID:456

Client Side (Angular): 客户端(角度):

 //LOGGED AS USER 123 $http.post('www.domain.com/api/user/123') .then(function (data) { // here I should receive the data from user 123 }) 

The code above it's easy to do, but I want to rescrict this endpoint (from server side) only for user 123. If user 456 try to get that endpoint shoul be kicked. 上面的代码很容易做到,但是我只想为用户123(从服务器端)重写此端点。如果用户456尝试获取该端点,则该脚本将被踢出。 Example: 例:

 //LOGGED AS USER 456 $http.post('www.domain.com/api/user/123') .then(function (data) { // should return error (forbidden resource) }) 

As you can see, if your are logged as user 456, you could get data from "api/user/123", but you could get from "api/user/456" 如您所见,如果您以用户456身份登录,则可以从“ api / user / 123”获取数据,但是可以从“ api / user / 456”获取数据

I want to solve this from server side 我想从服务器端解决这个问题

QUESTION: 题:

What is the best way to do it with Node/Express/JWT ?? 使用Node / Express / JWT的最佳方法是什么?

I would use a different URL design. 我将使用其他URL设计。 Instead of having 而不是

www.domain.com/api/user/123

I would just have 我只有

www.domain.com/api/user

And discover the user ID from the authentication token or session ID that is sent with the request. 并从与请求一起发送的身份验证令牌或会话ID中发现用户ID。

I have seen lots of authorization/security bugs that originate from specifying identities in URLs. 我已经看到许多授权/安全性错误,这些错误源自指定URL中的身份。 If you think about it, it is essentially duplicating the user ID parameter since it appears once in the URL and once in the authentication token. 如果考虑一下,它实际上是在复制用户ID参数,因为它在URL中出现一次,在身份验证令牌中出现一次。 That kind of duplication often leads to problems with authorisation logic getting out of sync with itself. 这种重复通常会导致授权逻辑与自身不同步的问题。

Create middleware/authorize.js 创建中间件/authorize.js

const fs = require('fs');
const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
    console.log('in!');
    let key = fs.readFileSync('rsa_2048_pub.pem');
    // If you are using default HMAC key the line above would be something like this:        
    // let key = process.env.JWT_SECRET // nodemon.json file needed for this to work

    try{
        const token = req.headers.authorization.split(' ')[1]; //req.headers.token;
        console.log(token);
        var decoded = jwt.verify(token, key)
        console.log(decoded);

        // add validation code here...

        next();

    }catch(err){
      return res.status(401).json({error: err, message: 'Invalid token.'});
    }
};

In routes/users.js you will import your middleware and have something like this: 在routes / users.js中,您将导入中间件,并且具有以下内容:

const User = require('../models/user')
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const authorize = require('../middleware/authorize'); //import your middleware

// add your middleware call to your routes
router.route('/validate-token').get(authorize, function(req,res, next){
  console.log('out!');

  res.status(200).json({message: 'Valid token.'});
});

You can use your payload to store information like userId , admin : true/false to authorize access in your middleware. 您可以使用有效负载来存储诸如userIdadmin : true/false以授权对中间件的访问。

For a more complete authorization handling i recommend also using an authorization package like CASL together with JWT strategy. 为了获得更完整的授权处理,我还建议同时使用CASL之类的授权包以及JWT策略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM