Javascript 我如何使我的代码生成用于用户授权和权限的JWT令牌?

Javascript 我如何使我的代码生成用于用户授权和权限的JWT令牌?,javascript,node.js,express,jwt,Javascript,Node.js,Express,Jwt,我不知道如何使这项工作成功。我有两个文件,permissionCtrl.js和tokenCtrl.js。我正在使用Node.js/Express.js、Sequelize和Postgres 权限文件包含链接到令牌文件的hasPermission函数。hasPermission函数应该检查令牌文件中生成的令牌,并返回成功回调的结果或403响应以及如下所示的消息。成功时,它将根据用户的角色和访问级别授予用户对安全路由的访问权限。请注意,tokenCtrl.hasPermission.js已导入到此文

我不知道如何使这项工作成功。我有两个文件,
permissionCtrl.js
tokenCtrl.js
。我正在使用Node.js/Express.js、Sequelize和Postgres

权限文件包含链接到令牌文件的
hasPermission
函数。hasPermission函数应该检查令牌文件中生成的令牌,并返回成功回调的结果或403响应以及如下所示的消息。成功时,它将根据用户的角色和访问级别授予用户对安全路由的访问权限。请注意,
tokenCtrl.hasPermission.js
已导入到此文件

hasPermission.js

exports.hasPermission = (req, res, permission, success) => {
  const token = req.get('Authorization');
  const hasPermission = tokenCtrl.hasPermission(token, permission); //tokenCtrl.hasPermission not a function error here
  console.log('permission', permission);
  if (hasPermission) {
    return success();
  } else {
    res.status(403);
    return res.json({
      error: {
        status: 403,
        message: 'Unauthorized',
      },
    });
  }
};
const nJwt = require('njwt');
const secureRandom = require('secure-random');
const signingKey = secureRandom(512, {type: 'Buffer'}); // Create a highly random byte array of 256 bytes
const base64SigningKey = signingKey.toString('base64');

const claims = {
  iss: "mysite.com",  // The URL of your service
  sub: "users/user1234",    // The UID of the user in your system
  scope: "user, admins"
};

module.exports = {

  // Returns token
  getToken: (claims, signingKey) => {
    const jwt = nJwt.create(claims, signingKey, 'HS512');
    console.log(jwt);
    const token = jwt.compact();
     console.log("Token :" + token);
    return (token);
},

  // Returns result of token validation
    validateToken: (token, signingKey) => {
      nJwt.verify(token, signingKey, 'HS512', function(err, verifiedJwt){
        if(err){
          console.log(err); // Token has expired, has been tampered with, etc
        }else{
          console.log(verifiedJwt); // Will contain the header and body
        }
        return (verifiedJwt);
      });
  },

  token_post: (req, res) => {
  res.send(this.validateToken(req.header.Authorization, signingKey));
},

getSecret: () => {
  const secret = require('../config/secret.json').secret;
  console.log('secret', secret);
  return secret;
},

hasPermission: (token, resource) => {
  const result = this.validateToken(token, signingKey); //this.validateToken not a function error here
  console.log(result);
  if (result.name === 'JsonWebTokenError') {
    return false;
  } else if (result.permissions) {
    let permissionSet = new Set(result.permissions);
    console.log('permissions in token', JSON.stringify(permissionSet));
    return permissionSet.has(resource);
  } else {
    return false;
  }
}

}

tokenCtrl.js

exports.hasPermission = (req, res, permission, success) => {
  const token = req.get('Authorization');
  const hasPermission = tokenCtrl.hasPermission(token, permission); //tokenCtrl.hasPermission not a function error here
  console.log('permission', permission);
  if (hasPermission) {
    return success();
  } else {
    res.status(403);
    return res.json({
      error: {
        status: 403,
        message: 'Unauthorized',
      },
    });
  }
};
const nJwt = require('njwt');
const secureRandom = require('secure-random');
const signingKey = secureRandom(512, {type: 'Buffer'}); // Create a highly random byte array of 256 bytes
const base64SigningKey = signingKey.toString('base64');

const claims = {
  iss: "mysite.com",  // The URL of your service
  sub: "users/user1234",    // The UID of the user in your system
  scope: "user, admins"
};

module.exports = {

  // Returns token
  getToken: (claims, signingKey) => {
    const jwt = nJwt.create(claims, signingKey, 'HS512');
    console.log(jwt);
    const token = jwt.compact();
     console.log("Token :" + token);
    return (token);
},

  // Returns result of token validation
    validateToken: (token, signingKey) => {
      nJwt.verify(token, signingKey, 'HS512', function(err, verifiedJwt){
        if(err){
          console.log(err); // Token has expired, has been tampered with, etc
        }else{
          console.log(verifiedJwt); // Will contain the header and body
        }
        return (verifiedJwt);
      });
  },

  token_post: (req, res) => {
  res.send(this.validateToken(req.header.Authorization, signingKey));
},

getSecret: () => {
  const secret = require('../config/secret.json').secret;
  console.log('secret', secret);
  return secret;
},

hasPermission: (token, resource) => {
  const result = this.validateToken(token, signingKey); //this.validateToken not a function error here
  console.log(result);
  if (result.name === 'JsonWebTokenError') {
    return false;
  } else if (result.permissions) {
    let permissionSet = new Set(result.permissions);
    console.log('permissions in token', JSON.stringify(permissionSet));
    return permissionSet.has(resource);
  } else {
    return false;
  }
}

}

错误

  • 如代码注释所示,此处的this.validateToken不是函数错误

  • tokenCtrl.hasPermission不是代码注释中显示的函数错误


  • 注意:
    tokenCtrl
    文件中的getSecret函数正被其他文件使用。

    您正在运行与
    在箭头函数中的绑定方式相冲突的操作。 以前的函数在其内部作用域中创建了一个新的空
    this
    ,在箭头函数
    中,this
    绑定到封闭作用域。 因为您是在exports对象内声明函数,所以您可能希望
    this
    绑定到封闭对象,但不是

    我建议只需声明函数,然后将它们添加到导出中。 这样可以避免使用
    this
    ,只需调用validateToken函数即可

    const validateToken = (token, signingKey) => {
          nJwt.verify(token, signingKey, 'HS512', function(err, verifiedJwt){
            if(err){
              console.log(err); // Token has expired, has been tampered with, etc
            }else{
              console.log(verifiedJwt); // Will contain the header and body
            }
            return (verifiedJwt);
          });
      };
    
    const hasPermission = (token, resource) => {
      const result = validateToken(token, signingKey); //this.validateToken not a function error here
      console.log(result);
      if (result.name === 'JsonWebTokenError') {
        return false;
      } else if (result.permissions) {
        let permissionSet = new Set(result.permissions);
        console.log('permissions in token', JSON.stringify(permissionSet));
        return permissionSet.has(resource);
      } else {
        return false;
      }
    };
    
    module.exports = {
      vaildiateToken,
      hasPermission
    }
    

    谢谢你,杰克·皮尔斯。让我试一试