首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使代码生成用于用户授权和权限的JWT令牌?

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

Stack Overflow用户
提问于 2020-02-05 13:15:51
回答 1查看 123关注 0票数 0

我不知道如何使这件事成功。我有两个文件,permissionCtrl.jstokenCtrl.js。我使用的是nJWT、Node.js/Express.js、Sequelize & Postgres。

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

hasPermission.js

代码语言:javascript
复制
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',
      },
    });
  }
};

tokenCtrl.js

代码语言:javascript
复制
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;
  }
}

}

误差

  1. 如代码注释所示,this.validateToken不是函数错误
  2. 如代码注释所示,tokenCtrl.hasPermission不是函数错误

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

EN

回答 1

Stack Overflow用户

发布于 2020-02-05 15:15:51

您对this在箭头函数中的绑定方式产生了冲突。以前,函数在其内部作用域中创建了一个新的空this,在箭头函数中,this被绑定到封闭作用域。因为要在导出对象中声明函数,所以您可能期望this绑定到封闭对象,但不是。

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

代码语言:javascript
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60076709

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档