5

如何通过 Meteor.js 中的自定义令牌服务器进行身份验证?

是否有任何像 accounts-google 这样的包用于自定义令牌服务器,它通过将令牌端点、客户端 ID、秘密和范围作为配置参数来处理身份验证。

4

1 回答 1

5

我不知道通用的 oauth 包。但是为您的特定服务器编写一个包应该不会太难,因为有许多示例可供查看。

以accounts-github为例,这里是在客户端建立连接的代码。请注意端点 URL、客户端 ID、范围等。这将为您处理弹出窗口,但您可能希望包含自定义 CSS:

var loginUrl =
  'https://github.com/login/oauth/authorize' +
  '?client_id=' + config.clientId +
  '&scope=' + flatScope +
  '&redirect_uri=' + OAuth._redirectUri('github', config) +
  '&state=' + OAuth._stateParam(loginStyle, credentialToken);

OAuth.launchLogin({
  loginService: "github",
  loginStyle: loginStyle,
  loginUrl: loginUrl,
  credentialRequestCompleteCallback: credentialRequestCompleteCallback,
  credentialToken: credentialToken,
  popupOptions: {width: 900, height: 450}
});

这是服务器端的一个片段,完成了获取访问令牌的过程:

var getAccessToken = function (query) {
  var config = ServiceConfiguration.configurations.findOne({service: 'github'});
  if (!config)
    throw new ServiceConfiguration.ConfigError();

  var response;
  try {
    response = HTTP.post(
      "https://github.com/login/oauth/access_token", {
        headers: {
          Accept: 'application/json',
          "User-Agent": userAgent
        },
        params: {
          code: query.code,
          client_id: config.clientId,
          client_secret: OAuth.openSecret(config.secret),
          redirect_uri: OAuth._redirectUri('github', config),
          state: query.state
        }
      });
  } catch (err) {
    throw _.extend(new Error("Failed to complete OAuth handshake with Github. " + err.message),
                   {response: err.response});
  }
  if (response.data.error) { // if the http response was a json object with an error attribute
    throw new Error("Failed to complete OAuth handshake with GitHub. " + response.data.error);
  } else {
    return response.data.access_token;
  }
};

并利用令牌获取用户身份:

var getIdentity = function (accessToken) {
  try {
    return HTTP.get(
      "https://api.github.com/user", {
        headers: {"User-Agent": userAgent}, // http://developer.github.com/v3/#user-agent-required
        params: {access_token: accessToken}
      }).data;
  } catch (err) {
    throw _.extend(new Error("Failed to fetch identity from Github. " + err.message),
                   {response: err.response});
  }
};

githubaccounts-github包作为参考应该非常有用。

于 2015-02-26T21:54:14.883 回答