Search code examples
phpoauthwp-api

WP-API oAuth Server to Server Flow


I'm a little confused about the flow I need to use if trying to connect to a remote Wordpress WP-API from another server (in this case another WP instance on the same server). I am using the PECL oAuth package, and most of the code I gathered up from the docs at https://secure.php.net/manual/en/class.oauth.php.

This is tied into a wordpress save hook like this, so every time someone saves a post on SITE A, it will attempt to send some info over to SITE B:

add_action( 'save_post', 'CrossPollinate_Save',10,3);

Inside CrossPollinate_Save is this:

$client_key =               "....";
$client_secret =            "....";
$request_token_endpoint =   "http://..../oauth1/request";
$authorize_endpoint =       "http://..../oauth1/authorize";
$access_endpoint =          "http://..../oauth1/access";
$callback =                 $_SERVER['REQUEST_URI'];
$request_token =            ""; //populated later
$request_token_secret =     ""; //populated later


//STEP 1
$oauth = new OAuth($client_key, $client_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$request_token_info = $oauth->getRequestToken($request_token_endpoint);
if(!empty($request_token_info)) {
    logToFile("Response from getRequestToken", $request_token_info);
} else {
    logToFile("Failed fetching request token: ", $oauth->getLastResponse());
}

$request_token = $request_token_info["oauth_token"];
$request_token_secret = $request_token_info["oauth_token_secret"];

logToFile("request_token is: ", $request_token);
logToFile("request_token_secret is: ", $request_token_secret);

//STEP 2
$oauth->setToken($request_token, $request_token_secret);
$access_token_info = $oauth->getAccessToken($authorize_endpoint."?oauth_callback=".$callback);

if(!empty($access_token_info)) {
    logToFile("Got access token! ", $access_token_info);
} else {
    logToFile("Failed fetching access token: " . $oauth->getLastResponse());
}

I get an oauth_token and a oauth_token_secret from "step 1", great, that part works! When step 2 fires it ends up returning with a response that contains the markup for the login page. How do I tell oAuth to skip that step and just send the access token back to the redirect page?


Solution

  • I don't think there's a way around having to do the full 3-legged auth. I've found nothing to the contrary anyway and have just accepted that I'll have to do the redirect after getting the initial tokens.