Is there any documentation on how to write a REST client with IOAuth using the module? An example would be great.

Thanks

Comments

ronnbot’s picture

I have a function something like below to make oauth requests (implemented on D7 but should be similar):

function mymodule_make_request($endpoint, $args, $access_token, $post = false) {
  // assuming we have a valid access token object

  $sign = new OAuthSignatureMethod_HMAC('SHA1'); // sign method
  $authentication = new HttpClientOAuth($access_token->consumer, $access_token, $sign); // build the authentication object
  $client = http_client($authentication); // build http client with oauth authentication
  
  if (!$post) {
    $result = $client->get($endpoint, $args); // make a get call to an endpoint with the following args using oauth
  }
  else {
    $result = $client->post($endpoint, $args); // post args
  }
  // parse the result first and/or catch errors here ?
  return $result; 
}

Before being able to make oauth request, you'll need to do some stuff to get the access token.

Initiate oauth process by getting a request token and allowing user to give access to our 'app':

function mymodule_goto_auth_page($params = array()) {
  $consumer = DrupalOAuthConsumer::loadProviderByKey(variable_get('mymodule_consumer_key', ''), false); // load the consumer object based on the consumer key
  $client = new DrupalOAuthClient($consumer, null, null, OAUTH_COMMON_VERSION_1); // create oauth client for consumer; for this provider, we need oauth v1
  
  $req_token = $client->getRequestToken(); // get request token; we don't really need this but the client object needs it later and retains a copy 
  $auth_url = $client->getAuthorizationUrl(null, array('params' => $params));
  
  drupal_goto($auth_url); // the user is redirected to the oauth provider for authenticaltion
}

Then process the resulting access token by implementing hook_oauth_common_authorized:

function mymodule_oauth_common_authorized($consumer, $access_token, $request_token) {
  global $user;

  if ($consumer->key == variable_get('mymodule_consumer_key', '')) { // we got an access token for our consumer, do stuff with it
    if ($user->uid && $access_token->uid != $user->uid) {
      $access_token->uid = $user->uid; // associate access token to current user; load this later for the user when we need it
      $access_token->write();
    }
    drupal_goto('user'); // we should have a 'destination' here and will redirect there instead but just in case...
  }
}
Hugo Wetterberg’s picture

Status: Active » Closed (fixed)

Closing this as the question was answered.