簡體   English   中英

如何讓我的代碼為用戶授權和許可生成 JWT 令牌?

[英]How can I make my code to generate JWT token for user authorization and permission?

我不知道如何進行這項工作。 我有兩個文件, permissionCtrl.jstokenCtrl.js 我正在使用nJWT 、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',
      },
    });
  }
};

令牌控件.js

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文件中的 getSecret 函數正被其他文件使用。

您正在與箭頭函數中的this沖突。 以前的函數在其內部作用域中創建了一個新的空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
}

暫無
暫無

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

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