【问题标题】:Sails JS policy doesn't respondSails JS 策略没有响应
【发布时间】:2018-12-17 12:36:39
【问题描述】:

我在制定 Sails Js 政策时遇到问题。它应该充当任何发送的请求和目标控制器之间的中间件。

预期

应验证在请求标头中发送的 JWT,解码播放负载并将其内容分配给可从任何控制器访问的 req.user 变量。

问题

当我使用先前生成的 JWT(使用邮递员)发送 Barear Token 授权类型请求时,我没有从后端服务器收到任何答复(甚至没有 500)。

我构建了什么

登录策略:

module.exports = async function (req, res, next) {

  var token;

  // Check if authorization header is present
  if(req.headers && req.headers.authorization) {

    // If so, isolate each parts
    var parts = req.headers.authorization.split(' ');
    if(parts.length == 2) {
        var scheme = parts[0];
        var credentials = parts[1];

        if(/^Bearer$/i.test(scheme)) {
            token = credentials;
        }
    } else {... error return ...}

    // If all test succeed, use TokenService.verify
    var decoded = TokenService.verify(token);

    User.findOne({id: decoded.id}).exec((error, user) => {
      if (error) return res.serverError(error)
      if (user) {
        req.token = decoded;
        next();
      }
    });
};

我的令牌服务:

const jwt = require('jsonwebtoken');
const tokenSecret = 'secretissecret';

module.exports = {

[...]

verify: token => jwt.verify(token, tokenSecret)
};

政策配置:

module.exports.policies = {

'*': 'is-logged-in',

// Bypass the `is-logged-in` policy for:
'entrance/*': true,
'account/logout': true,
'deliver-contact-form-message': true,

};

最简单的目标控制器

module.exports = {

[Actions 2 description, no-inputs, exits]

 fn: async function (inputs, exits) {

   // Look up by the user.id
   var userRecord = await User.findOne({ id: this.req.token.id}) <== Fix here

   // If there was no matching user, respond thru the "unfound" exit.
   if(!userRecord) {
     throw 'unfound';
   }    

   return exits.success({
     user: userRecord
   });
  }
};

【问题讨论】:

    标签: sails.js jwt


    【解决方案1】:

    我通过这种方式解决了我的问题。

    为了访问 Actions2 中的请求 token 对象,我使用了 this.req.token

    【讨论】:

      【解决方案2】:

      您还需要在 config/policies.js 中注册您的策略

      sails web 应用模板示例:

      module.exports.policies = {
      
          '*': 'is-logged-in',
      
        // Bypass the `is-logged-in` policy for:
        'entrance/*': true,
        'account/logout': true,
        'view-homepage-or-redirect': true,
        'deliver-contact-form-message': true,
      
      };
      

      【讨论】:

      • 这是一个疏忽,我刚刚编辑了帖子。配置文件也已构建。
      • 我的策略现在运行良好(我已经编辑了帖子),但在控制器中我无法恢复我分配给req.token 参数的解码令牌 => 它未定义.有什么想法吗?
      猜你喜欢
      • 2020-10-27
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多