3条腿的OAuth被广泛运用在诸如新浪微博等需要用户授权访问用户资源的开放平台中。
但一些公共数据并不需要用户参与,在这样的情况,就退化成消费和服务两者之间的交互认证。
2条腿的OAuth(2-legged OAuth)提供一种简洁安全的解决方案。
下面是客户端/服务器的简单示例。
如果请求没有带server参数,则表现为客户端,发送请求给自己并添加server参数。
从而表现为服务端,接受请求,验证并返回处理信息。
<?php // a super-stripped down 2-leg oauth server/client example
//http://oauth.net/code/
//http://oauth.googlecode.com/svn/code/php/OAuth.php
require 'oauth.php';
$key = '1234';
$secret = 'ABCD';
$consumer = new OAuthConsumer($key, $secret);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1;
if($_GET['server']){
$method = $_SERVER['REQUEST_METHOD'];
$uri = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$sig = $_GET['oauth_signature'];
$req = new OAuthRequest($method, $uri);
//验证签名,因为是2legged OAuth,所以这里token为空
$valid = $sig_method->check_signature( $req, $consumer, null, $sig );
if(!$valid){
die('invalid sig');
}
echo 'orale!';
}else{
//call this file
$api_endpoint = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
//handle request in 'server' block above
$parameters = array('server'=>'true');
//请求签名
$req = OAuthRequest::from_consumer_and_token($consumer, null, "GET", $api_endpoint, $parameters);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$req->sign_request($sig_method, $consumer, null);//note: double entry of token
//get data using signed url
$ch = curl_init($req->to_url());
curl_exec($ch);
curl_close($ch);
}