Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
voxpelli wrote some code illustrating how to implement client-side authentication with the OAuth module and Http Client:
/**
* Implements hook_menu().
*/
function vptest_menu() {
$items['vptest/request'] = array(
'page callback' => '_vptest_test_request',
'access arguments' => array('access content'),
);
$items['vptest/access'] = array(
'page callback' => '_vptest_test_access',
'access arguments' => array('access content'),
);
return $items;
}
/**
* Create a request token and redirect user to authorization URL.
*/
function _vptest_test_request() {
// Load consumer object or create it.
$consumer = DrupalOAuthConsumer::load('bVAU7jXKSL7vgnyayuiLZiGXZfoevZ8R', FALSE);
if (!$consumer) {
$consumer = new DrupalOAuthConsumer('bVAU7jXKSL7vgnyayuiLZiGXZfoevZ8R', 'N7LiwonhxUFs7RrwxEnizc2Doc7afPRx');
$consumer->write();
}
// Create request token.
$sig_method = DrupalOAuthClient::signatureMethod();
$client = new DrupalOAuthClient($consumer, NULL, $sig_method);
$request_token = $client->getRequestToken('http://sandbox.local/oauth/request_token', array(
'callback' => 'http://d7.local/vptest/access',
));
$request_token->write();
// Not actually necessary.
$_SESSION['vptest_request_key'] = $request_token->key;
// Get authorization URL and redirect the user.
$auth_url = $client->getAuthorizationUrl('http://sandbox.local/oauth/authorize', array(
'callback' => 'http://d7.local/vptest/access',
));
drupal_goto($auth_url);
}
/**
* Finalize access.
*/
function _vptest_test_access () {
// The user is coming from the (external) authorization page.
// Load request token, created in the previous function.
$consumer = DrupalOAuthConsumer::load('bVAU7jXKSL7vgnyayuiLZiGXZfoevZ8R', FALSE);
$request_token = DrupalOAuthToken::loadByKey($_GET['oauth_token'], $consumer, OAUTH_COMMON_TOKEN_TYPE_REQUEST);
// Get an access token, using the values provided in GET in the URL.
$client = new DrupalOAuthClient($consumer, $request_token);
$verifier = isset($_GET['oauth_verifier']) ? $_GET['oauth_verifier'] : NULL;
$access_token = $client->getAccessToken('http://sandbox.local/oauth/access_token', array('verifier' => $verifier));
// We won't need the request token any longer.
$request_token->delete();
// Store access token for later use, no need to authenticate again.
$access_token->write();
// Now we completed the authentication process, we can make
// an actual request using the provider API to retrieve data.
$sig_method = DrupalOAuthClient::signatureMethod();
$auth = new HttpClientOAuth($consumer, $access_token, $sig_method, TRUE, TRUE);
$formatter = new HttpClientBaseFormatter(HttpClientBaseFormatter::FORMAT_JSON);
$client = new HttpClient($auth, $formatter);
$result = $client->post('http://sandbox.local/oauthlogin/api/user/info');
print '<pre>';
var_dump($result);
print '</pre>'; die;
}