在自定义API中处理FB访问令牌的最佳实践

时间:2017-01-24 12:18:46

标签: php facebook facebook-php-sdk restful-url

我开发了一个restful api,其中客户端提供了一个facebook用户ID(比如myapi/get_user/123),API必须检索用户的公共信息,比如姓名,生日等。这已经完成了。

当前代码

$fb = new Facebook\Facebook([
        'app_id' => $fbSettings['app_id'],
        'app_secret' => $fbSettings['app_secret'],
        'default_graph_version' => $fbSettings['default_graph_version']
]);

$token = 'EAAD...';

try {
  // Returns a `Facebook\FacebookResponse` object
  $fbResponse = $fb->get('/' . $request->getAttribute('id') . '?fields=link, name, birthday', $token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    return $response->withStatus(500)->withJson(['msg' => $e->getMessage()]);
  exit;
}

$user = $fbResponse->getGraphUser();
return $response->withJson($user);

我的问题是我不知道处理访问令牌的最佳方法是什么。令牌应该由客户提供吗?在这种情况下,应该在同一个请求中传递为param(例如:myapi/get_user/123?token=ABC123),或者应该执行另一个api调用(假设myapi/register_token/ABC123)来打破无状态的原则。

我正在寻找处理访问令牌的最佳方式(或最佳实践)。

1 个答案:

答案 0 :(得分:1)

传递访问令牌的最佳方法是在授权请求标头中:

StringConverter<File> converter = new StringConverter<File>() {

    @Override
    public String toString(File file) {
        return file.getName();
    }

    @Override
    public File fromString(String string) {
        // not used by CheckBoxTreeCell:
        return null ;
    }
};

treview_Base.setCellFactory(tv -> {
    CheckBoxTreeCell<File> cell = new CheckBoxTreeCell<>();
    cell.setConverter(converter);
    return cell ;
});