Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to refresh Reddit OAuth 2.0 access token

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?

like image 803
Peter Hudec Avatar asked Mar 07 '13 21:03

Peter Hudec


2 Answers

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.

like image 148
inket Avatar answered Nov 15 '22 15:11

inket


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);
like image 2
tony Avatar answered Nov 15 '22 15:11

tony