node.js - 使用 JWT 进行环回身份验证

标签 node.js jwt loopbackjs passport.js

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

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

而且我不清楚我的下一步是什么。我有工作:

  • 用户“登录” - 生成 JWT
  • 用户使用用户名/密码登录(即将停用)
  • 在环回中工作的 ACL 实现(当我访问 ACL 保护的资源时,我得到了预期的 4xx 错误)
  • 我的 JWT token 在请求 header 中正确 (?)

我需要:

  • 基于 JWT token ,具有与环回 ACL 兼容的角色的有效用户

非常感谢您的帮助

最佳答案

结果证明解决方案比我想象的要简单得多。对于初学者,环回确实使用自己的 jwt webtoken 来保持(无状态)用户 session 。建立身份后(在我的情况下,从我的 JWT token 中提取手机号码)我只需要查找成员并生成环回 native JWT token 。我的端点定义是这样的:

  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);
          })
        }
      });
    }
  }

像魅力一样工作

关于node.js - 使用 JWT 进行环回身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474196/

相关文章:

javascript - npm Node 编码

javascript - Node.js 中的 Hash_hmac 等效项

c# - Identity Server 4 - 角色策略不起作用

python - 使用 Python 中的服务帐户创建 DfpClient

javascript - 自定义js文件中的环回模型访问

node.js - 如何使用 Telegram bot API 请求用户的实时位置?

node.js - Firebase 通知控制台在 Node.js 中等效

http - 如何根据 HTTP 请求获取响应 header ?

node.js - 为 PUT 请求环回 beforeRemote

node.js - 有时环回当前上下文为空