与 parse-server 和 auth0 的自定义身份验证集成 [英] Custom authentication integration with parse-server and auth0

查看:28
本文介绍了与 parse-server 和 auth0 的自定义身份验证集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 auth0.com 与开源解析服务器结合使用.

I would like to use auth0.com in conjunction with the open source-parse server.

我目前的方法是通过 iOS 的 Lock 库使用他们的标准登录名从 auth0 获取令牌.使用该令牌,我想在我的解析服务器上调用自定义身份验证方法,该方法检查令牌是否有效以及是否会登录用户.

My current approach is to obtain the token from auth0 by using their standard login through the Lock library for iOS. With that token I would like to call a custom authentication method on my parse-server, that checks whether the token is valid and if it is will log in the user.

我的问题是几乎没有关于为解析服务器编写自定义 oauth 的文档.

My problem is that there is almost no documentation on writing custom oauth for parse-server.

到目前为止,我有这个用于我的自定义身份验证的代码.

So far, I have this code for my custom auth.

var Parse = require('parse/node').Parse;

function validateAuthData(authData, options) {
  console.log('validateAuthData()');
  return new Promise((resolve, reject) => {
    try {
      var decoded = jwt.verify(authData.access_token, opions.sharedSecret);
      if (authData.id === decoded.sub) {
        resolve({});
      }
      throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Unauthorized');
    } catch(e) {
      throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, e.message);
    }
  });
}

function validateAppId(appIds, authData) {
  console.log('validateAppId()');
  return Promise.resolve();
}

module.exports = {
  validateAppId: validateAppId,
  validateAuthData: validateAuthData
};

但是,它不起作用,我也不明白如何使用此代码对特定用户进行身份验证.解析服务器是否进行数据库查找以将特定身份验证数据与特定用户相匹配?另外,如何使用自定义身份验证注册新用户.当用户尝试登录但他还不存在于我的解析数据库中时会发生什么?

However, it doesn't work and also I don't understand how this code can be used to authenticate a specific user. Does the parse-server do database look-ups to match the specific auth data to a specific user? Also, how can I register a new user with custom auth. What happens when a user tries to log in but he doesn't exist yet in my parse database?

另一种似乎是this,使用规则auth0.com.有什么区别以及规则如何运作?我对身份验证、oauth 和 jwt 的经验很少.

An alternative seems to be this, using a rule an auth0.com. What are the differences and how would the rule work? I have very little experience with authentication and oauth and jwt's.

最后,我正在使用这个 从我的 iOS 客户端调用我的自定义身份验证.但是,这也不起作用,但我不确定是由于 iOS 部分还是因为我的自定义身份验证尚未起作用.

Lastly, I am using this to call my custom auth from my iOS client. However this doesn't work either, but I am not sure whether it is due to the iOS part or because my custom auth isn't working yet.

总而言之,我在处理看起来相当简单的事情时遇到了麻烦.我想使用 auth0 作为我的身份验证提供程序,并且我想将它集成为 parse-server,因为我非常欣赏 parse 和客户端 sdk 的便利性.我相当肯定更多人有类似的问题,但是我还没有找到任何关于如何正确执行此操作的明确资源.

In conclusion, I am having trouble with something that seems rather easy. I want to use auth0 as my authentication provider and I want to integrate it was the parse-server, since I really appreciate the convenience around parse and the client sdk's. I am fairly certain that more people have a similar problem, however I have not found any definitive resource on how to properly do this.

更多链接

推荐答案

迟到的答案,但我正在解决同样的问题,并遇到了这篇文章:

late answer but I was solving the same problem and came across this post:

Auth0 具有您可以在登录时运行的规则.我已经从 https://github 修改了他们的示例之一.com/auth0/rules/blob/master/src/rules/parse.js,将 API 端点提取为常量.

Auth0 has rules you can apply that run when the login occurs. I've modified their example one from https://github.com/auth0/rules/blob/master/src/rules/parse.js, extracting the API endpoint into a constant.

function(user, context, callback) {
  // run this only for the Parse application
  // if (context.clientID !== 'PARSE CLIENT ID IN AUTH0') return callback(null, user, context);

  const request = require('request');

  const MY_API = 'https://subdomian.back4app.io';
  const PARSE_APP_ID = '*********';
  const PARSE_API_KEY = '**********';
  const PARSE_USER_PASSWORD = 'REPLACE_WITH_RANDOM_STRING'; // you can use this to generate one http://www.random.org/strings/

  const username = user.email || user.name || user.user_id; // this is the Auth0 user prop that will be mapped to the username in the db

  request.get({
      url: `${MY_API}/login`,
      qs: {
        username: username,
        password: PARSE_USER_PASSWORD
      },
      headers: {
        'X-Parse-Application-Id': PARSE_APP_ID,
        'X-Parse-REST-API-Key': PARSE_API_KEY
      }
    },
    function(err, response, body) {
      if (err) return callback(err);

      // user was found, add sessionToken to user profile
      if (response.statusCode === 200) {
        context.idToken[`${MY_API}/parse_session_token`] = JSON.parse(body).sessionToken;
        return callback(null, user, context);
      }

      // Not found. Likely the user doesn't exist, we provision one
      if (response.statusCode === 404) {
        request.post({
            url: `${MY_API}/users`,
            json: {
              username: username,
              password: PARSE_USER_PASSWORD
            },
            headers: {
              'X-Parse-Application-Id': PARSE_APP_ID,
              'X-Parse-REST-API-Key': PARSE_API_KEY,
              'Content-Type': 'application/json'
            }
          },
          function(err, response, body) {
            if (err) return callback(new Error('user already exists'));

            // user created, add sessionToken to user profile
            if (response.statusCode === 201) {
              context.idToken[`${MY_API}/parse_session_token`] = body.sessionToken;
              return callback(null, user, context);
            }
            return callback(new Error(username + ' The user provisioning returned an unknown error. Body: ' + JSON.stringify(body)));
          });
      } else {
        return callback(new Error('The login returned an unknown error. Status: ' + response.statusCode + ' Body: ' + body));
      }
    });
}

我正在用 JS 编写 SPA,所以我有一些客户端代码来处理 Auth0 登录,(替换 'https://subdomian.back4app.io' 和您自己的解析服务器的 API 地址 - 与上述 Auth0 规则中使用的值相同).注意Parse.User.become 函数,它将Auth0 规则中创建的会话ID 分配给当前解析用户:

I'm writing a SPA in JS, so I have some client side code that handles the Auth0 login, (replace 'https://subdomian.back4app.io' with your own parse server's API address - the same value as used in the above Auth0 rule). Note the Parse.User.become function, which assigns the session id created in the Auth0 rule to the current parse User:

handleAuthentication() {
  this.auth0.parseHash((err, authResult) => {
    if (authResult && authResult.accessToken && authResult.idToken) {
      this.setSession(authResult);
      Parse.User.become(authResult.idTokenPayload['https://subdomian.back4app.io/parse_session_token']);
      history.replace('/');
    } else if (err) {
      history.replace('/home');
      console.log(err);
    }
  });
}

这篇关于与 parse-server 和 auth0 的自定义身份验证集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆