Java中的两条腿OAuth2示例?

时间:2011-04-28 15:39:42

标签: java android oauth

我有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

TADA!它就像一个冠军。我试图在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;
  }
}

在后端验证签名时,请务必在所有中包含您在请求中传递的参数。我坐着看着#34;无效的签名。预期的签名基本字符串POST&amp; ...&#34;错误一小时,直到我弄清楚如何设置System.setProperty(&#34; debug&#34;,&#34; 1&#34;);并在Java端看到了原始的基本字符串。这个功能现在已经足够好了,但是我仍然希望看到它在维护的库下是如何工作的。

1 个答案:

答案 0 :(得分:1)

由于您已经提到过joauth,我已经编写了documentation以允许使用JOAuth进行OAuth 1授权。

我希望这会对你有所帮助。