【发布时间】:2011-06-22 22:25:53
【问题描述】:
我有一个 example web.py app 提供 REST 服务 + OAuth2。在 Python 中,客户端应用程序会经历生成 OAuth2 消费者、请求、对其进行签名等过程。类似这样(伪代码参考,不完整):
import json
import time
import oauth2
import urllib2
# Set up the POST variables
method = 'POST'
url = 'https://localhost/service/rest'
parameters = {
'username' : username,
'password' : password
}
# Generate our Consumer object
consumer = oauth2.Consumer( key = KEY, secret = SECRET )
# Add additional parameters required by OAuth
parameters['oauth_version'] = "1.0"
parameters['oauth_nonce'] = oauth2.generate_nonce()
parameters['oauth_timestamp'] = int(time.time())
parameters['oauth_consumer_key'] = consumer.key
# Generate and sign the request
oauth = oauth2.Request( method = method, url = url, parameters = parameters )
signature_method = oauth2.SignatureMethod_HMAC_SHA1()
oauth.sign_request( signature_method, consumer, None )
# Shoot it off to the webserver
req = urllib2.Request( BASE_URL, oauth.to_postdata() )
result = urllib2.urlopen( req ).read()
json_result = json.loads( result )
print json_result
多田!它像冠军一样工作。我正在尝试在 Java 下做同样的事情,特别是在 Android 上,但此时我会采取任何措施。我看到的所有示例都集中在使用三足身份验证的公共 OAuth2 API 上,或者集中在 Web 服务的服务器端配置上。
有人能同情我并指出一个使用 BasicHttpContext、DefaultHttpClient 和朋友的 Java 中同样简单的示例吗?
稍后编辑
回答您自己的问题可能被认为是一种不好的形式,但这里是如何做我所要求的。事实证明,两脚oauth确实是OAuth v1.0的功能,所以半废弃的oauth.signpost库可以轻松搞定。我尝试使用最近维护的 joauth 库,但找不到任何好的示例来说明如何只做我想要的部分。这段代码实际上分布在我的代码中的三四个不同的 java 文件中,但我是为了这个伪代码示例一起完成的。
import ...
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
public class RestClient {
private OAuthConsumer oauth_consumer = null;
private DefaultHttpClient http_client;
private static final String consumer_key = "something";
private static final String consumer_secret = "something_else";
public RestClient( Context context ) {
// Instantiate our custom http client with our trusted key
this.http_client = new DefaultHttpClient();
// Instantiate an oauth_consumer
this.oauth_consumer = new CommonsHttpOAuthConsumer( consumer_key, consumer_secret );
}
public POST( String url, Map params ) {
// Initialize our post request
HttpPost httppost = new HttpPost( url );
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
// This iterates through the parameters and stores them for use
List<NameValuePair> name_value_pairs = new ArrayList<NameValuePair>(2);
Iterator iter = params.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry pairs = (Map.Entry)iter.next();
name_value_pairs.add(
new BasicNameValuePair( (String)pairs.getKey(), (String)pairs.getValue() )
);
}
try {
// Put our parameters in our Post
httppost.setEntity( new UrlEncodedFormEntity( name_value_pairs ) );
// sign our request
this.oauth_consumer.sign( httppost );
// Yoiks, and away!
HttpResponse response = http_client.execute( httppost );
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
JSONObject json = new JSONObject( convertStreamToString(instream) );
// Closing the input stream will trigger connection release
instream.close();
return json;
} catch ( aBunchOfShit e) {
e.printStackTrace();
}
}
return null;
}
}
当您在后端验证您的签名时,请务必包含所有您在请求中传递的参数。我坐在那里看着“无效的签名。预期的签名基础字符串 POST&...”错误一个小时,直到我弄清楚如何设置 System.setProperty("debug","1");并在 Java 端看到了原始的基本字符串。这目前已经足够好用了,但我仍然想看看它在维护的库下是如何工作的。
【问题讨论】:
-
我不明白你如何使用
context作为new DefaultHttpClient的参数 DefaultHttpClient 不接受 HttpParams 吗? -
您使用的代码遵循 OAuth 1.0a 授权,但您的标题要求使用 2-Legged OAuth。
-
@LuxuryMode 这只是一个错字。很抱歉造成混乱!