使用JWT进行环回认证

时间:2015-12-26 18:47:53

标签: node.js jwt loopbackjs passport.js

我正在尝试了解如何将自定义JWT路由安装到环回安全模型中。我的应用程序有一个涉及SMS的身份验证“舞蹈”,可以使用excellent description生成有效的JWT令牌。我正在使用jsonwebtoken,事情按预期工作。获得令牌后,我的angular.js客户端发送带有Authorisation: JWT ..token..标头中每个请求的令牌(发现有冲突的文档,一个说JWT,一个承载,但我可以想出来)。

现在我想在loopback应用程序中使用令牌。我想使用ACL系统环回提供。我确实阅读了以下资源:

我不清楚接下来的步骤是什么。我有工作:

  • 用户'登录' - 生成JWT
  • 使用用户名/密码进行用户登录(待退休)
  • 在环回中使用ACL实现(当我访问受ACL保护的资源时,我得到了,正如预期的那样4xx错误)
  • 我的JWT令牌在请求标题中正确(?)

我需要:

  • 基于JWT令牌,具有与回送ACL兼容的角色的有效用户

非常感谢帮助

1 个答案:

答案 0 :(得分:3)

解决方案结果证明要简单得多。对于初学者来说,loopback确实使用自己的jwt webtokens来保持(无状态)用户会话。在建立身份后(在我的情况下从我的JWT令牌中提取移动号码)我只需要查找该成员并生成回送本机JWT令牌。我的端点定义如下:

  Member.remoteMethod(
    'provideSMSToken', {
      accepts: [{
        arg: 'mobilenumber',
        type: 'string',
        description: 'Phone number including +65 and no spaces'
      }, {
        arg: 'token',
        type: 'string',
        description: 'the token received through SMS'
      }],
      returns: {
        arg: 'token',
        type: 'string'
      },
      description: 'provide SMS token to confirm login',
      http: {
        path: '/smsauthenticate',
        verb: 'post'
      },
      isStatic: true
    }

  );

provideSMSToken函数类似:

 // Exchange the SMS Token with a login token
  Member.provideSMSToken = function(mobilenumber, token, cb) {
    var app = Member.app;
    // CHeck if the token does exist for the given phone number
    // if yes, check for the respective memeber

    if (!app.smsVerificationToken || !app.smsVerificationToken[mobilenumber] || app.smsVerificationToken[mobilenumber] !== token) {
      var wrongToken = new Error("Wrong or missing token");
      cb(wrongToken, "Wrong or missing token");
    } else {
      var timetolive = 86400;
      Member.lookupByPhone(mobilenumber, function(err, theOne) {
        if (err) {
          cb(err, "Sorry, no such member here!");
        } else {
          // We can provide a token now for authentication
          // using the default createAccessToken method
          theOne.createAccessToken(timetolive, function(err, accesstoken) {
            cb(err, accesstoken);
          })
        }
      });
    }
  }

像魅力一样工作