簡體   English   中英

保護Express和NodeJ上的路由

[英]Securing routes on Express and NodeJs

我正在尋找“限制”特定路線的最佳方法,我將通過一個示例進行說明:

我有兩個用戶:

-user1 ID:123

-user2 ID:456

客戶端(角度):

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

上面的代碼很容易做到,但是我只想為用戶123(從服務器端)重寫此端點。如果用戶456嘗試獲取該端點,則該腳本將被踢出。 例:

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

如您所見,如果您以用戶456身份登錄,則可以從“ api / user / 123”獲取數據,但是可以從“ api / user / 456”獲取數據

我想從服務器端解決這個問題

題:

使用Node / Express / JWT的最佳方法是什么?

我將使用其他URL設計。 而不是

www.domain.com/api/user/123

我只有

www.domain.com/api/user

並從與請求一起發送的身份驗證令牌或會話ID中發現用戶ID。

我已經看到許多授權/安全性錯誤,這些錯誤源自指定URL中的身份。 如果考慮一下,它實際上是在復制用戶ID參數,因為它在URL中出現一次,在身份驗證令牌中出現一次。 這種重復通常會導致授權邏輯與自身不同步的問題。

創建中間件/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.'});
    }
};

在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.'});
});

您可以使用有效負載來存儲諸如userIdadmin : true/false以授權對中間件的訪問。

為了獲得更完整的授權處理,我還建議同時使用CASL之類的授權包以及JWT策略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM