无法刷新Reddit OAuth 2.0访问令牌

9

我无法刷新Reddit访问令牌。

当我向https://ssl.reddit.com/api/v1/access_token发送以下请求时:

Content-Type: application/x-www-form-urlencoded
Authorization: #####
client_secret=#####&grant_type=refresh_token&client_id=#####&refresh_token=#####

我收到200状态码,但内容为{"error": "invalid_request"}

根据OAuth 2.0规范Reddit规范,我的操作都是正确的。

我已经尝试过没有client_idclient_secret进行操作,但结果相同。

我是否漏掉了什么?

2个回答

22

Reddit的OAuth实现非常独特(并且不太好)。

刷新reddit令牌所需的参数为:

  1. client_id
  2. client_secret
  3. grant_type(=refresh_token)
  4. refresh_token
  5. scope
  6. state
  7. duration
  8. redirect_uri

您还需要使用client_id作为登录和client_secret作为密码的基本HTTP身份验证标头。

我不得不查看reddit的源代码才能弄清楚我的请求中缺少了什么……在琐碎的事情上浪费了很多开发时间。


我相信这个 bug 现在已经修复了,你只需要 grant_type 和 refresh_token 参数。但是如果刷新令牌不属于与 client_id 相同的应用程序,则会返回 400。 - Nathan

2

如果有人需要更明确的答案:

以下是我在PHP中的操作方式。

    $authorizeUrl = 'https://ssl.reddit.com/api/v1/access_token';
    $clientId = "YOUR_CLIENT_ID";
    $clientSecret = "YOUR_CLIENT_SECRET";

    $post = array(
        "client_id" => $clientId,
        "client_secret" => $clientSecret,
        "grant_type" => "refresh_token",
        "refresh_token" => "STORED_REFRESH_TOKEN_VALUE",
        "scope" => "identity",
        "state" => "WHATEVER_VALUE",
        "duration" => "temporary",          
        "redirect_uri" => "https://example.com/reddit",
    );

    $payload = http_build_query($post);

    $ch = curl_init($authorizeUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, $clientId . ":" . $clientSecret);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);        

    print_r($result);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接