9

I cannot refresh the Reddit access token.

When I send following request to 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=#####

I get status 200 but content is {"error": "invalid_request"}.

According to OAuth 2.0 spec and Reddit spec I do everything right.

I've also tried it without client_id and client_secret with the same result.

Am I missing something?

Community
  • 1
  • 1
Peter Hudec
  • 2,462
  • 3
  • 22
  • 29

2 Answers2

22

Reddit's OAuth implementation is really unique (and not in a good way).

The necessary parameters for refreshing tokens on reddit are:

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

You'll also need the basic HTTP authentication header with client_id as login and client_secret as password.

I had to look up reddit's source code to figure out what was missing from my requests... So much development time lost on trivial matters.

inket
  • 1,641
  • 16
  • 21
  • I believe this bug is now fixed, and you only need the grant_type and refresh_token parameters. It will return a 400 if the refresh token is not for the same app as the client_id though – Nathan Feb 07 '17 at 06:23
2

In case anyone is looking for more explicit answer:

Here is how I did this in 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);
tony
  • 911
  • 9
  • 8