Custom authentication integration with parse-server and auth0

牧云@^-^@ 提交于 2019-12-08 17:38:12

问题


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

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.

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?

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.

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.

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.

Further Links

  • Parse user authenticated using Auth0
  • https://auth0.com/blog/2016/03/07/hapijs-authentication-secure-your-api-with-json-web-tokens/
  • https://github.com/ParsePlatform/parse-server/wiki/OAuth
  • https://jwt.io/introduction/

回答1:


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

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

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


来源:https://stackoverflow.com/questions/38069817/custom-authentication-integration-with-parse-server-and-auth0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!